5

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!

1

2 Answers 2

10

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) 
2
  • Wow...I don't understand the last line of code why it won't compile.
    – Steve Lam
    Jul 18, 2012 at 10:42
  • It is because both of the types returned must be of the same type as the assignment (in this case an Integer (i). In the example I gave one of the types is a string so this fails compilation.
    – Matt Wilko
    Mar 17, 2014 at 9:36
2

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.