Calling methods on uninitiated variables

If you don’t assign a value to an object variable, it will have the value Nothing (equivalent to null in C#). These two lines of code will therefore effectively do exactly the same thing, even though the second version will produce slightly more assembly:

Dim MyString As String

…and…

Dim MyString As String = Nothing

If you create an extension method on the String class, and you write it in such fashion that it can handle uninitialized variables, it will be able to do so. The extension is done to the type, not to the object. This is an example of a function that checks if a string is empty:

<System.Runtime.CompilerServices.Extension()> _
Public Function IsEmpty(ByVal S As String) As Boolean
   If S Is Nothing Then
      Return True
   Else
      Return (S = "")
   End If
End Function

When the above extension is present, the following piece of code…

Dim MyString As String = Nothing
Console.WriteLine(MyString.IsEmpty())

…displays the word True in your console window!

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *