Updated: 19/02/2005; 9:03:03.
Hannes 'Shorty' Decorte's Radio Weblog
Learning .Net and the Experiences doing so


zaterdag 19 februari 2005

Today I observed the following lines of code:

If ObjectAInstance1 Is Nothing Or ObjectAInstance1 Is ObjectA.Empty Then

End If

Where ObjectA.Empty returns New ObjectA().
What's wrong? Well the part ObjectAInstance1 Is ObjectA.Empty always returns false, even (what wasn't the case) if you override the Equals method in ObjectA class.

The developer actually wanted to do the following:

If ObjectAInstance1 Is Nothing Or ObjectAInstance1.Equals(ObjectA.Empty) Then

End If

But that doesn't work either cause if ObjectAInstance1 is Nothing then ObjectAInstance1.Equals(ObjectA.Empty) will result in a NullReferenceException.

To observe the difference of = and Is here is some code to run:

If "" = "" Then
MessageBox.Show("''=''")
End If

If "e" = "e" Then
MessageBox.Show("'e'='e'")
End If

If "" = String.Empty Then
MessageBox.Show("''= String.Empty")
End If

If New String("e", 1) = New String("e", 1) Then
MessageBox.Show("New String('e', 1) = New String('e', 1)")
End If

If New String("e", 1) = "e" Then
MessageBox.Show("New String('e', 1) = 'e'")
End If

If "" Is "" Then
MessageBox.Show("'' Is ''")
End If

If "e" Is "e" Then
MessageBox.Show("'e' Is 'e'")
End If

If "" Is String.Empty Then
MessageBox.Show("'' Is String.Empty")
End If

If New String("e", 1) Is New String("e", 1) Then
MessageBox.Show("New String('e', 1) Is New String('e', 1)")
End If

If New String("e", 1) Is "e" Then
MessageBox.Show("New String('e', 1) Is 'e'")
End If

If "".Equals("") Then
MessageBox.Show("''.Equals('')")
End If

If "".Equals(String.Empty) Then
MessageBox.Show("''.Equals(String.Empty)")
End If

If New String("e", 1).Equals(New String("e", 1)) Then
MessageBox.Show("New String('e', 1).Equals(New String('e', 1))")
End If

If New String("e", 1).Equals("e") Then
MessageBox.Show("New String('e', 1).Equals('e')")
End If

MSDN states
The Is operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the exact same object instance, result is True; if they do not, result is False.

Oh yeah and the VB Is is not the same as is in C#.


9:02:59 AM    comment []

© Copyright 2005 Hannes 'Shorty' Decorte.
 

February 2005
Sun Mon Tue Wed Thu Fri Sat
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28          
Jan   Mar


RSS Feed

Other .Net Bloggers

Bart De Smet
Jan Tielens
Patrick Verbruggen
Patrick Tisseghem
Tom van de Kerkhof's Bloggings
Tom's Corner
Yves Hanoulle

Aggregated Feeds

Belgian .NET Bloggers