DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

What's The IIF In C#

12.14.2011
| 4226 views |
  • submit to reddit
        C# has the "?" ternary operator, like other C-style languages. However, this is not perfectly equivalent to iif. There are two important differences.

To explain the first, this iif() call would cause a DivideByZero exception even though the expression is true because iif is just a function and all arguments must be evaluated before calling:
iif(true, 1, 1/0)
Another way, iif does not short circuit in the traditional sense, as your question indicates. On the other hand, this ternary expression does and so is perfectly fine:
(true)?1:1/0;
The other difference is that iif is not type safe. It accepts and returns arguments of type object. The ternary operator uses type inference to know what type it's dealing with

<a href="http://www.java-forums.org/blogs/eclipse-ide/"><strong>Eclipse IDE</strong></a> and <a href="http://www.java-forums.org/blogs/eclipse/"><strong>Eclipse</strong></a>