Tutorial :What does the ?? operator do? [duplicate]



Question:

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;  


Solution:1

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;  


Solution:2

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.


Solution:3

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.


Solution:4

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;  


Solution:5

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


Solution:6

The expression

value1 ?? value2  

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


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »