Visual Basic .NET Language

NullReferenceException

Remarks#

NullReferenceException is thrown whenever a variable is empty and one of its method/properties are referenced. To avoid this, be sure all variables are initialized correctly (new operator), and all methods returns a non-null value.

Uninitialized variable

BAD CODE

Dim f As System.Windows.Forms.Form
f.ShowModal()

GOOD CODE

Dim f As System.Windows.Forms.Form = New System.Windows.Forms.Form
' Dim f As New System.Windows.Forms.Form ' alternative syntax
f.ShowModal()

EVEN BETTER CODE (Ensure proper disposal of IDisposable object more info)

Using f As System.Windows.Forms.Form = New System.Windows.Forms.Form
' Using f As New System.Windows.Forms.Form ' alternative syntax
    f.ShowModal()
End Using

Empty Return

Function TestFunction() As TestClass
    Return Nothing
End Function

BAD CODE

TestFunction().TestMethod()

GOOD CODE

Dim x = TestFunction()
If x IsNot Nothing Then x.TestMethod()

Null Conditional Operator

TestFunction()?.TestMethod()

This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow