Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

Tags:

.net

vb.net

Quick question, of which the quickest and easiest answer may well be to rearrange related code, but let's see...

So I have an If statement (a piece of code which is a part of a full working solution written in C#) rewritten using VB.NET. I am aware the VB.NET IIf(a, b, c) method evaluates both b and a regardless of the trueness of the first evaluation, but this seems to be the case in my standard construct, too:

If (example Is Nothing Or example.Item IsNot compare.Item) Then
    'Proceed
End If

Or, rather, more appropriately:

If (example Is Nothing Or Not example.Item = compare.Item) Then
    'Proceed
End If

Here, if example is Nothing (null) then I still get an NullReferenceException - is this my fault, or is it something I just have to endure at the whim of VB.NET?

like image 210
Grant Thomas Avatar asked Jan 18 '11 10:01

Grant Thomas


People also ask

What is the syntax of if else if statement in VB net?

Syntax. If the Boolean expression evaluates to true, then the if block of code will be executed, otherwise else block of code will be executed.

What is an example of an if/then else statement?

The if / then statement is a conditional statement that executes its sub-statement, which follows the then keyword, only if the provided condition evaluates to true: if x < 10 then x := x+1; In the above example, the condition is x < 10 , and the statement to execute is x := x+1 .

What is IF THEN END IF structure in VB?

If the condition evaluates to true, then the block of code inside the If statement will be executed. If condition evaluates to false, then the first set of code after the end of the If statement (after the closing End If) will be executed.

How do you end an IF ELSE statement?

In the multiline syntax, the If statement must be the only statement on the first line. The ElseIf , Else , and End If statements can be preceded only by a line label. The If ... Then ... Else block must end with an End If statement.


2 Answers

It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

So you probably want:

If (example Is Nothing OrElse Not example.Item = compare.Item) Then
    'Proceed
End If

I can't say it reads terribly nicely, but it should work...

like image 195
Jon Skeet Avatar answered Oct 11 '22 12:10

Jon Skeet


OrElse is the short-circuited equivalent of Or

like image 41
Richard Szalay Avatar answered Oct 11 '22 11:10

Richard Szalay