Posts C# Basics - Null Coalescing (??) Operator
Post
Cancel

C# Basics - Null Coalescing (??) Operator

The ?? operator is called null-coalescing operator.

This operator is used to provide a default value if the value of the operand on the left-hand side of the operator is null.

The usage is as follows: var variable = operand ?? default value;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Program
{
    public int Value { get; set; }

    public Program(int value)
    {
        Value = value;
    }

    static void Main(string[] args)
    {
        string input = GetName();

        string name = input ?? "Alen Alex";

        string inputAddress = GetAddress();

        string address = inputAddress ?? "NA";

        Program p1 = GetProgram();

        Program p2 = p1 ?? new Program(10);

        Console.WriteLine(name);

        Console.WriteLine(address);

        Console.WriteLine(p2.Value);
    }

    private static string GetAddress()
    {
        return "<<Proper Address>>";
    }

    private static Program GetProgram()
    {
        return null;
    }

    private static string GetName()
    {
        return null;
    }
}

The output of this would be:

1
2
3
Alen Alex
<<Proper Address>>
10

Reference: Microsoft Docs

This post is licensed under CC BY 4.0 by the author.