views:

230

answers:

4

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 the 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?

+16  A: 

Yup:

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

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

Pete
+2  A: 

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

Keith
Heh, must have been my subconscious reaching out. Knew I had seen it somewhere.
Abe Miessler
A: 

Yes, it's called the Null Coalescing operator:

?? Operator (C# Reference) (MSDN)

Kev
+7  A: 

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).

Jon Skeet