I was having trouble using the VB.NET
IIF() feature today, it was not behaving the way that I expected it would in that it was still evaluating both results no matter whether or not the expression was returning True or False.
var myVar = true; var mySecondVar = myVar ? 5 : 10;
This, however, is not the case in VB.NET. After reading this article by Leon Bambrick, the truth began to reveal itself. It the article, Leon explains that in VB.NET
IIF() is a function rather than a feature of the language. Therefore, each of the parameters for the function are evaluated before the function is executed, making
IIF() thoroughly useless for evaluating anything but already defined values.
For example, I was trying to use
IIF() to check if there was a logged in user, and to return different values accordingly:
Dim Username As String = IIF(Membership.GetUser.Email Is Nothing, "", Membership.GetUser.Email)
This of course was producing an
"Object reference not set to an instance of an object" error, because even though
Membership.GetUser.Email was nothing, the
IIF() function needed to execute
Membership.GetUser.Email before the
IIF() comparison could be run, because it is the FalsePart parameter of the function.
Basically, if you are ever doing something like this it is better to use the long way instead of using IIF, like so:
Dim Username As String = String.Empty If Membership.GetUser.Email Is Nothing Then Username = "" Else Username = Membership.GetUser.Email End If
And you shouldn’t have any more issues!
var a = (c == 0) ? 0 : (b/c);