Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Calling methods on uninitiated variables

2012-01-21

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!

Categories: Visual Studio 11

Leave a Reply

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



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips