.netvb.net

VB.NET language and Nothing : why is it the way it is?


This is a question about the VB.NET language. Since I am using it every day, I just try to understand the motivations behind some of its constructs.

I just find out that this line :

If myObject Is Nothing then

is as correct as this one is :

If Nothing Is myObject Then

Same results. Using ildasm, we can see that these lines are translated to :

if myObject = null then

and

if null = myObject then

Well, but, in VB.NET, you cannot write :

if myObject = Nothing Then

The compiler will not accept that.

Mmm, to me, If Nothing Is myObject is much more less obvious than If myObject = Nothing.

Why did VB.NET authors just think the opposite ? Any hint ?


Solution

  • The problem you're running into is that VB.Net differentiates the 2 types of object comparison. Namely Reference and Value comparison.

    The "Is" operator in VB.Net is used for reference comparison. This can be used when the values in question are both reference types or nullables. Attempting to compare value types i this manner will result in a compilation error.

    The "=" operator is used for Value comparison. The value comparison can only be used on types which define an explicit =, <> operator pair in their class definition. The actual implementation of the equality depends on the implementation of the operator.

    C# takes a different approach in that it uses == for both value and reference comparison. Which is used is dependent upon a couple of factors including the type of the values being compared and the implementation of certain equality methods.