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
|
|