Export (0) Print
Expand All

?? Operator (C# Reference)

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

A nullable type can represent a value from the type’s domain, or the value can be undefined (in which case the value is null). You can use the ?? operator’s syntactic expressiveness to return an appropriate value (the right hand operand) when the left operand has a nullible type whose value is null. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

For more information, see Nullable Types (C# Programming Guide).

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

class NullCoalesce
    static int? GetNullableInt()
        return null;

    static string GetStringValue()
        return null;

    static void Main()
        int? x = null;

        // Set y to the value of x if x is NOT null; otherwise, 
        // if x = null, set y to -1. 
        int y = x ?? -1;

        // Assign i to return value of the method if the method's result 
        // is NOT null; otherwise, if the result is null, set i to the 
        // default value of int. 
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // Display the value of s if s is NOT null; otherwise,  
        // display the string "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
© 2014 Microsoft