Select Page

The C# null-coalescing operator ?? supplies a fallback when a value is null. In color ?? "White", the expression returns color when it has a value and "White" otherwise.

The examples use C# 8 or later for nullable reference annotations and ??=. The ?? operator itself also works in older C# versions.

Give a property a default display value

This complete console example gives a color property a default value. #nullable enable turns on nullable reference analysis, and string? marks values that can be null. The property accepts null in its setter and supplies the fallback in its getter. The string? property annotation is conservative: callers are told that null is possible, although this getter always returns a string.

#nullable enable
using System;

class Program
{
    static string? _colors;

    static string? Colors
    {
        get { return _colors ?? "White"; }
        set { _colors = value; }
    }

    static void Main()
    {
        Console.WriteLine(Colors);
        Colors = "Purple";
        Console.WriteLine(Colors);
        Colors = null;
        Console.WriteLine(Colors);
    }
}
White
Purple
White

The backing field starts as null. Reading Colors returns White. After assigning Purple, the getter returns Purple. Assigning null restores the fallback on the next read.

_colors ?? "White" returns a value without changing _colors. The right operand is evaluated only when the left operand is null.

Use ??= when you want to store the fallback

The null-coalescing assignment operator ??= assigns a fallback when the variable is null. This example also shows that an empty string has a value and that a nullable integer can use zero as a fallback.

#nullable enable
using System;

class Program
{
    static void Main()
    {
        string? color = null;
        Console.WriteLine(color ?? "White");
        Console.WriteLine(color is null);
        color ??= "White";
        Console.WriteLine(color);
        color = "";
        Console.WriteLine((color ?? "White").Length);
        int? count = null;
        Console.WriteLine(count ?? 0);
    }
}
White
True
White
0
0

The first expression prints White while color remains null, so the next line prints True. color ??= "White" stores White. After assigning an empty string, ?? keeps it, and its length is zero.

For a fallback on null, empty, or whitespace-only text, test with string.IsNullOrWhiteSpace. An ordinary non-nullable int cannot be the left operand of ??; the example uses int?.

Continue learning

For text that represents a number, use int.TryParse to validate and convert it. Null handling and numeric format validation solve different input problems.

References

See Microsoft’s null-coalescing operators reference and nullable reference types documentation.

Share This