Null-coalescing ?? operator in C#

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand 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.

static void Main()
        // ?? operator example. 
        int? x = null;

        // y = x, unless x is null, in which case y = -1. 
        int y = x ?? -1;

        // Assign i to return value of method, unless 
        // return value is null, in which case assign 
        // default value of int to i. 
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // ?? also works with reference types.  
        // Display contents of s, unless s is null,  
        // in which case display "Unspecified".
        Console.WriteLine(s ?? "Unspecified");

The ?? operator checks whether the value provided on the left side of the expression is null, and if so it returns an alternate value indicated by the right side of the expression.  If the value provided on the left side of the expression isn't null, then it returns the original value.

For example, let’s assume we have a string variable “message”.  We could check whether message was null, and return an alternate value using the code below:

Because the “message” variable above wasn’t null, the “result” variable is assigned the original “hello world” message value.

In the code snippet below, however, message is a null value, and so the ?? operator will return the alternate value we’ve provided:

The ?? operator works for both reference types and value types.  For example, below we are checking whether the nullable integer “number” variable is null.  Because it isn’t, the result will be the original value (55):

If “number” is null, then result is assigned the value 0:



Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s