Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid running into false part in IIF?

Tags:

.net

vb.net

iif

I am trying to use the IIF in vb.net, here is my code

Dim arr as new MyClass("ABC")
MyAnotherMethod(IIf(arr.SelectedValue.Count < 1, Nothing, arr.SelectedValue(0).Value),"xxx","yyy","zzz")

the above IIF will run into the true part, but after I run this code, I got the following message:

Index was outside the bounds of the array.

I think the reason is that although true part should be run, the arr.SelectedValue(0).Value has passed into the IIF, so the false part is still being referenced.

Does there any logic like "andalso" and suitable for my case? In order to avoid running the false part.

Thanks a lot!

like image 695
Steve Lam Avatar asked Jan 16 '23 02:01

Steve Lam


2 Answers

You need to use the IF Operator instead of the IIF Function

"An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation"

It is also type safe whereas IIF is not so you should really be using this. Have a look at these worked examples:

    Dim i As Integer

    'compiles if option strict is off (this is bad)
    i = IIf(True, "foo", 4) 

    'compiles even if option strict on, but results in a runtime error (this is even worse)
    i = CInt(IIf(True, "foo", 4)) 

    'won't compile (this is good because the compiler spotted the mistake for you)
    i = If(True, "foo", 4) 
like image 138
Matt Wilko Avatar answered Jan 26 '23 00:01

Matt Wilko


IIf is deprecated, use If exactly in its place:

result = If(condition, truePart, falsePart)

For completeness’ sake, there is also a second way of using it:

result = If(mayBeNothing, Alternative)

These two operators correspond to C#’s conditional operator … ? … : … and its null coalesce operator … ?? ….

But @dasblinkenlight is correct: in your case it would be more appropriate to use FirstOrDefault instead of a conditional.

like image 26
Konrad Rudolph Avatar answered Jan 26 '23 01:01

Konrad Rudolph