What is the meaning of the "??"

45

I was looking at some codes and I came across the ?? operator:

static int? GetNullableInt()
{
    return null;
}

int y = x ?? -1;

What's the difference between the first code and the second one?

    
asked by Mathi901 16.12.2014 в 17:17
source

1 answer

49

It is called null-coalescing . In some contexts it is called the "Elvis" operator.

If the first operand is null, the result of the expression will be the second operand. Otherwise the result will be the first operand.

int y = x ?? -1;

is the same as doing:

int y = (x == null) ? -1 : x;

If you have a value that can correctly and interestingly replace a null value that would probably cause a problem in use, it is a simple way to do the override.

Wikipedia article .

int?

The two codes do completely different things, you can not compare them. The first one just returns a null, which probably has some very specific reason in the found code. What's different about it is int? .

This is a type. The full type name is int? (it reads "nullable int"). This is only used in types by value . These types are created as structs , and can not have a null value, since null is just a reference to an invalid memory location (usually 0). So these types were created to allow per-valued types to have a null.

These types are called nullable types or nullable types. In the background it is a struct composed basically of two members, the type value, in this case a int and a bool field to tell if it is null or not. If it is null, the value should not be read.

This types are actually obtained with the class Nullable . So int? is just a syntactic sugar for Nullable<int> .

Complement

In C # 6 there is also ?. ( null-propagating ). It will be used to decide whether the next operand will be evaluated or not. For example:

x.ExecuteAlgo();

will result in an exception if x is null. However if you use the new operator the method will simply not run. This is useful in some scenarios where you do not want something to run, if the object is in an invalid state by nullity:

x?.ExecuteAlgo();

Executes the method only if the x object is initialized correctly. This code is the same thing to do:

if (x != null)
    x.ExecuteAlgo();

A more complex example:

x?.y?.z;

is equivalent to this:

(x == null ? null : (x.y == null ? null : x.y.z))

To test this download Visual Studio 2015 or which has the new compiler and .NET Compiler Platform .

Learn more on this question .

    
answered by 16.12.2014 / 17:21
source