Posted By

bernicestockstill on 03/15/18


Versions (?)

Operator (C# Reference)

 / Published in: C#

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");
  1. 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 nullable 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. 2
  3. For more information, see Nullable Types.
  5. The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

Report this snippet  

You need to login to post a comment.