Null-Coalescing Operator ??

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. 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.

    1 using System;

    2 class NullCoalesce

    3 {

    4     static int? GetNullableInt()

    5     {

    6         return null;

    7     }

    8 

    9     static string GetStringValue()

   10     {

   11         return null;

   12     }

   13 

   14     static void Main()

   15     {

   16         // ?? operator example.

   17         int? x = null;

   18 

   19         // y = x, unless x is null, in which case y = -1.

   20         int y = x ?? -1;

   21 

   22         // Assign i to return value of method, unless

   23         // return value is null, in which case assign

   24         // default value of int to i.

   25         int i = GetNullableInt() ?? default(int);

   26 

   27         string s = GetStringValue();

   28         // ?? also works with reference types.

   29         // Display contents of s, unless s is null,

   30         // in which case display "Unspecified".

   31         Console.WriteLine(s ?? "Unspecified");

   32     }

   33 }

For more information, see Nullable Types (C# Programming Guide).

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.


Original MSDN Post

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