What is the "??" operator for? [duplicate]

It's the null coalescing operator. It was introduced in C# 2.

The result of the expression a ?? b is a if that's not null, or b otherwise. b isn't evaluated unless it's needed.

Two nice things:

  • The overall type of the expression is that of the second operand, which is important when you're using nullable value types:

    int? maybe = ...;
    int definitely = maybe ?? 10;
    

    (Note that you can't use a non-nullable value type as the first operand - it would be pointless.)

  • The associativity rules mean you can chain this really easily. For example:

    string address = shippingAddress ?? billingAddress ?? contactAddress;
    

That will use the first non-null value out of the shipping, billing or contact address.


It's called the "null coalescing operator" and works something like this:

Instead of doing:

int? number = null;
int result = number == null ? 0 : number;

You can now just do:

int result = number ?? 0;

That is the coalesce operator. It essentially is shorthand for the following

x ?? new Student();
x != null ? x : new Student();

MSDN Documentation on the operator

  • http://msdn.microsoft.com/en-us/library/ms173224.aspx

It's the new Null Coalesce operator.

The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.

You can read about it here: http://msdn.microsoft.com/en-us/library/ms173224(VS.80).aspx