2

Using vb.net the following code throws a null pointer exception but the expression should guarantee that match is not null.

repeater.DataSource = IIf(collection IsNot Nothing AndAlso match IsNot Nothing, collection.FindAll(match), collection)

Replacing this with regular if-else construct no error is thrown:

If collection IsNot Nothing AndAlso match IsNot Nothing Then
    repeater.DataSource = collection.FindAll(match)
Else
    repeater.DataSource = collection
End If

Are both path's evaluated in an ternary operator?

djmj
  • 5,579
  • 5
  • 54
  • 92

2 Answers2

3

If Operator (Visual Basic) - MSDN

An If operator that is called with three arguments works like an IIf function except that it uses short-circuit evaluation. An IIf function always evaluates all three of its arguments

Habib
  • 219,104
  • 29
  • 407
  • 436
1

Yes, both sides are evaluated, you should avoid the IIf() syntax and use the If() instead, because If() will short-circuit with AndAlso.

For more information read the accepted answer to VB.NET - IIF(,,) - Both “sides” are evaluated. What situations should I watch out for?.

Community
  • 1
  • 1
Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • I am glad that you accepted the answer, feel free to up-vote the answer as well. :-) – Karl Anderson Sep 05 '13 at 15:11
  • Better would be to use the IF operator in VB.Net which _does_ short circuit. IIF is just a normal function. Habib's answer is the best one. – Chris Dunaway Sep 05 '13 at 16:32
  • @ChrisDunaway - I mentioned that `If` will short-circuit in my answer, but you are free to advocate whichever answer you feel is best. – Karl Anderson Sep 05 '13 at 16:34
  • I don't see any mention of the IF operator in your post. I see "If-Else" mentioned in conjunction with the AndAlso keyword, but I didn't understand that you meant the IF operator. I only advocated Habib's answer because he specifically mentioned the IF operator in VB. – Chris Dunaway Sep 05 '13 at 16:37
  • @ChrisDunaway - understood. Updating answer to correctly reflect the terminology. – Karl Anderson Sep 05 '13 at 18:54