开发者

Coalesce operator in C#?

开发者 https://www.devze.com 2023-01-20 10:26 出处:网络
I think i remember seeing something similar to the ?: ternary operator in C# that only had two parts to it and would return the variable value if it wasn\'t null and a default value if it was.Somethin

I think i remember seeing something similar to the ?: ternary operator in C# that only had two parts to it and would return the variable value if it wasn't null and a default value if it was. Something like this:

tb_MyTextBox.Text = o.Member ??SOME OPERATOR HERE?? "default";

Basically t开发者_开发知识库he equivalent of this:

tb_MyTextBox.Text = o.Member != null ? o.Member : "default";

Does such a thing exist or did I just imagine seeing this somewhere?


Yup:

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

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-coalescing-operator


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消