C#: Null coalescing operator

C# has a ?? operator, which is called the ‘Null coalescing operator’. The ?? operator is a infix operator used on nullable types or objects. If the operand on the left is null, it returns the value of the expression on the right, else it is the left operand itself.

Here is an example showing how it is used.

    int result;
    int? num = null; // num is null
    result = num ?? 10; // sets result to 10.
    Console.WriteLine(result);
    num = 5; // num is 5.
    result = num ?? 10; // sets result as 5.
    Console.WriteLine(result);

Comments

Leave a comment