views:

3184

answers:

5

What's the iif equivalent in c#? or similar short circuit?

+2  A: 

the ternary operator

bool a = true;

string b = a ? "if_true" : "if_false";

Causas
A: 

It's the ternary operator ?

string newString = i == 1 ? "i is one" : "i is not one";
Jon Limjap
+15  A: 

VB.NET:

IIf(someBool, "true", "false")

C#

someBool ? "true" : "false";
Kevin Pang
While this is true for simple expressions, the two forms are not exactly equivalent if there are side effects in the alternative expressions. Iif(t, foo(), bar()) will call both foo() and bar(), while t ? foo() : bar() will only call either foo() or bar() but not both. See Joel Coehoorn's answer to this question for more information.
Greg Hewgill
+2  A: 

Also useful is the coalesce operator ??:

VB:

Return Iif( s IsNot Nothing, s, "My Default Value" )

C#:

return s ?? "My Default Value";
John Gibb
+12  A: 

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.

Joel Coehoorn
VB9 does support a true ternary operator.If(SomeBool, MessageBox.Show("True"), MessageBox.Show("False"))As seen here: http://community.bartdesmet.net/blogs/bart/archive/2007/08/31/visual-basic-9-0-the-if-ternary-operator.aspx
Snarfblam
I mention it in the last paragraph, but the question was specifically about IIf().
Joel Coehoorn