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);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s