Confused with conditional and logical operators - VB.net
I'm kind of new to VB.net, and since I just finished a C# course, the lack of parentheses creates a lot of confusion on how to write certain combinations of operators.
The C# equivalent of the line I am trying to reproduce in VB would be like this :
if ( (a == 0 && b != null) || (a == 1 && c != null) )
I'm have no idea how to write this in VB, I开发者_如何学Python've tried many combinations of And, Or, AndAlso, OrElse, etc. but I can't achieve the desired result.
I can't find any clear example of C# v.s. VB.net comparison on operators, and the notes I have aren't helpful either.
Can someone help me figure this out?
The equals operator is ==
in C# and =
in VB.
if ( (a == 0 && b != null) || (a == 1 && c != null) )
statement; // One single statement only
or
if ( (a == 0 && b != null) || (a == 1 && c != null) ) {
statement; // Any number of statements
}
This online conversion tool will convert it to VB for you:
If (a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing) Then
statement
End If
C# &&
translates to AndAlso
in VB.
C# ||
translates to OrElse
in VB.
With these operators the evaluation stops as soon as the result is determined. This is known as "short-circuit" evaluation. E.g. in a && b
the result is known to be false
if a
is false
, and b
will not be evaluated. This is especially important when the evaluation has side effects, like performing database queries, raising events or modifying data. It is also useful in conditions like these person != null && person.Name == "Doe"
where the second would throw an exception if the first term evaluates to false
.
The equivalent of the VB And
and Or
Boolean operators that do not use short-circuit evaluation are &
and |
in C#. Here all the terms will always be evaluated.
If (a = 0 Or b = 0 And c = 0) Then
statement
End If
if (a = 0 | b = 0 & c = 0) {
statement;
}
The vb.net equivalent would be
If (a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing ) Then
Note in c#, it should be a == 0
and not a = 0
Checkout this post with a comprehensive comparison.
if ( (a = 0 && b != null) || (a = 1 && c != null) )
Is equivilent to:
if ( ( a = 0 AndAlso b IsNot Nothing) OrElse (a = 1 AndAlso c IsNot Nothing) )
精彩评论