85

Is there an IIf equivalent in C#? Or similar shortcut?

d219
  • 2,707
  • 5
  • 31
  • 36
Saif Khan
  • 18,402
  • 29
  • 102
  • 147
  • 5
    I think you meant "short cut", rather than "short circuit" (which has a specific meaning regarding boolean operators) - am I right? – Blorgbeard May 05 '09 at 01:54

7 Answers7

127

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 difference, the false-part argument for this IIf() call causes a DivideByZeroException, even though the boolean argument is True.

IIf(true, 1, 1/0)

IIf() is just a function, and like all functions all the arguments must be evaluated before the call is made. Put another way, IIf() does not short circuit in the traditional sense. On the other hand, this ternary expression does short-circuit, and so is perfectly fine:

(true)?1:1/0;

The other difference is IIf() is not type safe. It accepts and returns arguments of type Object. The ternary operator is type safe. It uses type inference to know what types it's dealing with. Note you can fix this very easily with your own generic IIF(Of T)() implementation, but out of the box that's not 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 like C#'s ternary operator. It uses type inference to know what it's returning, and it really is an operator rather than a function. This means there's no issues from pre-evaluating expressions, even though it has function semantics.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • 3
    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 – snarf May 05 '09 at 01:19
  • 1
    I mention it in the last paragraph, but the question was specifically about IIf(). – Joel Coehoorn May 05 '09 at 01:27
67

VB.NET:

If(someBool, "true", "false")

C#

someBool ? "true" : "false";
Kevin Pang
  • 41,172
  • 38
  • 121
  • 173
  • 2
    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 May 05 '09 at 01:49
  • 1
    Updated answer to use VB.NET's "If" function instead of "IIf" so that the two code blocks are equivalent. – Kevin Pang Jun 07 '11 at 18:30
13

the ternary operator

bool a = true;

string b = a ? "if_true" : "if_false";
Marc
  • 16,170
  • 20
  • 76
  • 119
Ris Adams
  • 1,345
  • 4
  • 13
  • 25
  • i'd add a comment there that that's string b= (a ? "asdf" : "dsrs"); i.e. then it's possible to better understand how the thing works, and to see that it's not something really weird and nonsensical like (string b=a) ? "sdf" : "sdsdf"). – barlop Apr 20 '16 at 11:14
10

Also useful is the coalesce operator ??:

VB:

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

C#:

return s ?? "My Default Value";
John Gibb
  • 10,603
  • 2
  • 37
  • 48
6
booleanExpression ? trueValue : falseValue;

Example:

string itemText = count > 1 ? "items" : "item";

http://zamirsblog.blogspot.com/2011/12/c-vb-equivalent-of-iif.html

animuson
  • 53,861
  • 28
  • 137
  • 147
Zamir
  • 61
  • 1
  • 1
1

It's the ternary operator ?

string newString = i == 1 ? "i is one" : "i is not one";
Jon Limjap
  • 94,284
  • 15
  • 101
  • 152
0

It's limited in that you can't put statements in there. You can only put values(or things that return/evaluate to values), to return

This works ('a' is a static int within class Blah)

Blah.a=Blah.a<5?1:8;

(round brackets are impicitly between the equals and the question mark).

This doesn't work.

Blah.a = Blah.a < 4 ? Console.WriteLine("asdf") : Console.WriteLine("34er");
or
Blah.a = Blah.a < 4 ? MessageBox.Show("asdf") : MessageBox.Show("34er");

So you can only use the c# ternary operator for returning values. So it's not quite like a shortened form of an if. Javascript and perhaps some other languages let you put statements in there.

barlop
  • 12,887
  • 8
  • 80
  • 109
  • Yes, because it's setting a value, not invoking a method. You could use `Action` to do what you want though. – Kieran Foot Oct 04 '20 at 20:37
  • @KieranFoot WriteLine is a method. Been a while, but If `iif` or the ternary operator, let you put a return value in there like `Blah.a = Blah.a < 4 ? Console.WriteLine("asdf"); return 1: Console.WriteLine("34er") ; return 2;` then if it allowed that, it'd work, but apparently it doesn't. And yeah it's still setting a value, and no it's not calling any new method there. – barlop Oct 04 '20 at 21:17
  • You could easily make it an inline if that executes one of 2 actions as I said. – Kieran Foot Apr 29 '22 at 18:43