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!
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With