Short-circuit evaluation in C# and VB.NET
In my early years of college as a CS student I learned about
short-circuit
evaluation.
Short-circuit evaluation denotes that the second argument is
only evaluated if the first argument does not suffice the value of the
expression. I found out that short-circuit evaluation in C# is different
from VB.NET. Consider the following codes.
Here, if MyFunctionA() returns false and MyFunction() will
not be executed.
if (MyFunctionA() && MyFunctionB())
{
}
Same with this, if MyFunctionA() returns
true, MyFunctionB() will not be evaluated.
if (MyFunctionA() || MyFunctionB())
{
//Some codes here
}
In VB.NET, it’s different. Even if
MyFunctionA() returns false, MyFunctionB() will also evaluated. There’s no
short-circuit evaluation happened.
If (MyFunctionA() And
MyFunctionB()) Then
'Some codes here
End If
Same with this,
If (MyFunctionA() Or
MyFunctionB()) Then
'Some codes here
End If
Here’s the catch, to be able to achieve the
short-circuit evalution in VB.NET use AndAlso and OrElse keyword.
If (MyFunctionA() AndAlso
MyFunctionB()) Then
If (MyFunctionA() OrElse
MyFunctionB()) Then
I wonder why the keywords (instead of using And only and Or for VB.NET) are different from these 2 languages considering
they were both from MS....