What is the meaning of the operator "?"

Asked

Viewed 5,366 times

50

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

static int? GetNullableInt()
{
    return null;
}

int y = x ?? -1;

What is the difference between the first code and the second?

1 answer

57


He is called null-coalescing. In some contexts he is called the operator "Elvis".

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 perform the substitution.

Wikipedia article.

int?

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

This is a guy. The full name of the guy is int? (reads "voidable int"). This is only used in types per value. These guys are created like structs, and cannot have a null value, since null is only a reference to an invalid memory location (usually 0). So these types were created to allow types by value to have a null.

These guys are called nullable types or cancellable types. At the bottom is a struct composed basically of two members, the value of the type, in case one int and a field bool to say whether it is null or not. If it is null, the value should not be read.

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

Complement

In C# 6 there is also the ?. (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. But if you use the new operator the method will simply not be executed. 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();

It will execute the method only if the object x is initialized correctly. This code is the same as doing:

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 above that has the new compiler and the .NET Compiler Platform.

Learn more in that question.

  • 2

    That one null-propagating is it would be a hand on the wheel if it had in php :(

  • 1

    Very good the examples

Browser other questions tagged

You are not signed in. Login or sign up in order to post.