Uh, AndAlso?
Since I’ve been doing some VB.NET lately in my current project I have noticed some of the differences between VB and C# that I may not have noticed before.
In C# this code is kosher:
string s = null;
if (s != null && s.Length > 0)
{
/* do stuff */
}
But in VB, this will throw a NullReferenceException.
Dim s As String = Nothing
if ((Not s = Nothing) And s.Length > 0) Then
‘ Do stuff
End If
The exception gets thrown because the And keyword still processes both expressions of the ‘If’ statement, even though after the first expression has been found to be false, the ‘If’ statement CAN’T be true. If you want to get an optimized ‘If’ statement, you have to use the really cool ‘AndAlso’ keyword, like this:
Dim s As String = Nothing
if ((Not s = Nothing) AndAlso s.Length > 0) Then
‘ Do stuff
End If
The code above will work with no exception. I think the reason that the behavior of the ‘And’ keyword was left this way for backward compatibility, although I can only come up with one pretty weak scenario where this would matter, if you were doing something like this:
Dim myObj as MyObject = New MyObject()
Dim s as String = String.Empty
if (s = Nothing And myObj.DoSomethingReallyImportantHere() ) Then
‘ Do stuff
End If
By using the ‘And’ keyword, seasoned VB people would expect the .DoSomethingReallyImportantHere() function to always get called, even though the first expression of the ‘If’ statement already ensured that the combined expression would be false. So to preserve backward compatibility we now have ‘AndAlso’, what a joy.
UPDATE: I’m a moron, see Joe’s comment below
Joe said,
Wrote on May 31, 2006 @ 4:39 am
Wouldnt this fail as well?
string s = null;
if (s != null & s.Length > 0)
{
/* do stuff */
}
ben said,
Wrote on May 31, 2006 @ 8:36 am
Joe, I feel like an idiot
You are correct, that does throw the same exception, I totally blanked that c# has similar operators. I think I just got caught up in the verbosity of VB and thinking that ‘AndAlso’ and ‘OrElse’ just sound so lame.