Coalesce operator in C#?

拟墨画扇 提交于 2019-12-03 06:05:07

Yup:

tb_myTextBox.Text = o.Member ?? "default";

http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx

Well, it's not quite the same as the conditional operator, but I think you're thinking of the null coalescing operator (??). (I guess you did say it was "similar" :) Note that "ternary" just refers to the number of operands the operator is - so while the conditional operator is a ternary operator, the null coalescing operator is a binary operator.

It broadly takes this form:

result = first ?? second;

Here second will only be evaluated if first is null. It doesn't have to be the target of an assignment - you could use it to evaluate a method argument, for example.

Note that the first operand has to be nullable - but the second doesn't. Although there are some specific details around conversions, in the simple case the type of the overall expression is the type of the second operand. Due to associativity, you can stack uses of the operator neatly too:

int? x = GetValueForX();
int? y = GetValueForY();
int z = GetValueForZ();

int result = x ?? y ?? z;

Note how x and y are nullable, but z and result aren't. Of course, z could be nullable, but then result would have to be nullable too.

Basically the operands will be evaluated in the order they appear in the code, with evaluation stopping when it finds a non-null value.

Oh, and although the above is shown in terms of value types, it works with reference types too (which are always nullable).

Funny you used "??SOME OPERATOR HERE??", as the operator you're looking for is "??", i.e.:

tb_MyTextBox.Text = o.Member ?? "default";

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, it's called the Null Coalescing operator:

?? Operator (C# Reference) (MSDN)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!