iif equivalent in c#

2020-01-28 03:10发布

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

7条回答
我命由我不由天
2楼-- · 2020-01-28 03:22

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.

查看更多
来,给爷笑一个
3楼-- · 2020-01-28 03:27

the ternary operator

bool a = true;

string b = a ? "if_true" : "if_false";
查看更多
The star\"
4楼-- · 2020-01-28 03:30

Also useful is the coalesce operator ??:

VB:

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

C#:

return s ?? "My Default Value";
查看更多
Root(大扎)
5楼-- · 2020-01-28 03:33

VB.NET:

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

C#

someBool ? "true" : "false";
查看更多
SAY GOODBYE
6楼-- · 2020-01-28 03:35

It's the ternary operator ?

string newString = i == 1 ? "i is one" : "i is not one";
查看更多
Anthone
7楼-- · 2020-01-28 03:37

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.

查看更多
登录 后发表回答