11.4.10

Iff statement in VB.NET



As a C# developer, I'm accustomed to using the one-line conditional statement; (condition) ? (true condition code) : (false condition code); So when I started to write VB.NET recently, which I abandoned several years ago, I found it nice to use the Iff function.

Any way, I was surprised by its behavior, until I came back to my common sense and realized that Iff is not a keyword in VB.NET but rather it's a function, like any other function.

The following statement will always cause a run-time error:

Dim x As MyObject
Dim y As Integer
x = Nothing
y = Iff(x IsNot Nothing, x.MyValue, 5)

You might wonder, why it causes a run-time error when I'm asking it to return 5 when x is nothing. But, in fact, because Iff is like any function, it receives 3 parameters; the first one is the condition, the second one is the value to be returned when the condition is true and the third is the value that should be returned when the condition is false. The last 2 parameters are always evaluated regardless of the condition.



No comments:

Post a Comment

Popular Posts