Is there an IIf
equivalent in C#? Or similar shortcut?
This question is related to
c#
.net
conditional-operator
iif-function
booleanExpression ? trueValue : falseValue;
Example:
string itemText = count > 1 ? "items" : "item";
http://zamirsblog.blogspot.com/2011/12/c-vb-equivalent-of-iif.html
VB.NET:
If(someBool, "true", "false")
C#
someBool ? "true" : "false";
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.
Also useful is the coalesce operator ??:
VB:
Return Iif( s IsNot Nothing, s, "My Default Value" )
C#:
return s ?? "My Default Value";
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";
Source: Stackoverflow.com