Many months ago, I discussed the fact that we were finally planning to come up with a true ternary conditional operator that would allow short-circuited conditional expressions. (Just as a quick recap: the current problem with the IIF function is that it evaluates all the arguments since it is just a regular method call. So “IIF(x Is Nothing, “Empty”, x.Name)” will throw an exception if x is Nothing, because we still evaluate x.Name.)
At the time, we were considering taking the IIF function and making it intrinsic. In the end, this looked like it would just be too big of a compatibility problem. There were lots and lots of subtleties around the return type and the short-circuiting behavior that were going to pose problems. So instead we simply reused an existing keyword and invented a whole new operator–the If operator. The If operator works just the way you’d expect it–it evaluates the first operand and if it is True, evaluates and returns the second operand. If it it’s False, then it evaluates the third operand and returns that. There is also a binary form of the If operator that takes a reference type or a nullable value type as its first operand. If the value is not Nothing, then the first operand is returned. If the value is Nothing, the second operand is returned. This is useful for doing a database coalesce operation, something like “If(x.Name, “<no name>”)”.
The result type of an If operation depends on the types of the two operands that might be returned from the operation. In general, we pick the wider of the two types. If the two types don’t convert to each other, then you get an error. (For example, if you did “If(<boolean>, <integer>, <long>)”, the result type would be long. If you did “If(<boolean>, <Button>, <string>)”, you’d get an error because there was no conversion between Button and string.)
One question people might have is, “why the parenthesis?” More than a few people have suggested an expression form of the If statement, something like “x = If y Is Nothing Then “<none>” Else y” or other variations that weren’t delimited by parenthesis. In the end, most everything that didn’t use parenthesis as delimiters just ended up looking funny when you put it in an If statement (“If z = If y Is Nothing Then “<none>” Else y Then…”) or funny when you strung a few of them together using AndAlso/OrElse. For what it’s worth…
The If operator won’t appear in Orcas until Beta2, unfortunately. So you’ll still have to wait a bit longer…
(And, as a final piece of trivia, why is the IIF function called “IIF?” It stands for “Immediate If“.)