What's the iif equivalent in c#? or similar short circuit?
the ternary operator
bool a = true;
string b = a ? "if_true" : "if_false";
It's the ternary operator ?
string newString = i == 1 ? "i is one" : "i is not one";
VB.NET:
IIf(someBool, "true", "false")
C#
someBool ? "true" : "false";
Also useful is the coalesce operator ??:
VB:
Return Iif( s IsNot Nothing, s, "My Default Value" )
C#:
return s ?? "My Default Value";
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)
Put 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. Note that you can fix this very easily with a generic implementation, but out of the box that's the way it is.
If you really want iif() in C#, you can have it:
object iif(bool expression, object truePart, object falsePart)
{return expression?truePart:falsePart; }
or a generic/type-safe implementation:
T iif<T>(bool expression, T truePart, T falsePart)
{ return expression?truePart:falsePart;}
On the other hand, if you want the ternary operator in VB, Visual Studio 2008 and later provide a new If
operator that works more like C#'s ternary. It uses type inference to know what it's returning, and it's an operator rather than a function so there's no pesky divide-by-zero issues.