开发者

What does the ?? operator do? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

What is the “??” operator for?

I have recently come across the ??开发者_运维技巧 operator in C#. What does this operator do and when would someone use it?

Example:

string name = nameVariable ?? string.Empty;


The ?? operator basically means "or if it is null, blah". It is equivalent to:

string name = (nameVariable == null) ? string.Empty : nameVariable;

Which, if you're not familiar with the syntax, is basically:

string name;
if (nameVariable == null)
    name = string.Empty;
else
    name = nameVariable;


It's a null-coalescing operator It will right part if the left one is null.

The interesting fact is that you can even use it like this:

string temp = (first ?? second).Text

and it will return Text property of the 'second' variable if 'first' is null.


It has the catchy title of the Null Coalescing Operator. What it does is evaluate an expression and then if the expression is null it returns the right-hand operand, otherwise it returns the left-hand operand (ie. the original value).

Using your example as a basis you'd get these results:

string nameVariable = "Diplodocus";
string name = nameVariable ?? string.Empty;
// assigns name the value "Diplodocus"

And...

string nameVariable = null;
string name = nameVariable ?? string.Empty; 
// assigns name the value String.Empty;

Note you can use it with any reference or nullable type, not just strings.


It is equivalent to checking for null and setting the value to something if the first one is. Your statement above is equivalent to:

string name = nameVariable == null ? string.Empty : nameVariable;


It is a null reference check if nameVariable is null it would return an empty string.


The expression

value1 ?? value2

returns value1 if value1 is a value different from null, and returns value2 if value1 equals null.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜