Search code examples
.netsequenceiif

Why IIF is evaluating the two sides ? .NET


I'm trying to use the IIF in a simple mode:

 Dim MyList As List(Of Double) = New List(Of Double)
 Dim ret As Double

 ret = IIf(MyList.Count > 0, MyList.Max(), 0)

There is no elements in MyList but a System.InvalidOperationException is thrown, "Sequence has no elements". Why IIF is evaluating the two sides ?

Thanks!


Solution

  • Because that is the old VB6 function, use the If operator which does short-circuit evaluation:

    ret = If(MyList.Count > 0, MyList.Max(), 0)