C# Null Coalescing Operator and its Uses

Posted by: Suprotim Agarwal , on 8/2/2011, in Category C#
Views: 189808
Abstract: The C# Null Coalescing Operator (??) is a binary operator that simplifies checking for null values. It can be used with both nullable types and reference types. In this article, we will see how to use the Null coalescing operators in practical scenarios.

The C# Null Coalescing Operator (??)  is a binary operator that simplifies checking for null values. It can be used with both nullable types and reference types. It is represented as x ?? y which means if x is non-null, evaluate to x; otherwise, y. In the syntax x ?? y

  • x is the first operand which is a variable of a nullable type.
  • y is the second operand which has a non-nullable value of the same type.

While executing code, if x evaluates to null, y is returned as the value. Also remember that the null coalescing operator (??) is right-associative which means it is evaluated from right to left. So if you have an expression of the form x ?? y ?? z, this expression is evaluated as x?? (y?? z).

Note: Other right-associative operators are assignment operators, lambda and conditional operators.

Now with an overview of the C# Null Coalescing operator, let us see how to use the Null coalescing operators in practical scenarios.

 

Scenario 1 – Assign a Nullable type to Non-Nullable Type

Consider the following piece of code where we are assigning a nullable type to a non-nullable type.

C# Nullable Type

In the code above, if the nullable type (in our case ‘a’) has a null value and the null value is assigned to a non-nullable type (in our case ‘b’), an exception of type InvalidOperationException is thrown, as shown below:

image

One way to resolve this error is to use a IF..ELSE condition and check the value of the nullable type before assigning it to the non-nullable type

C# Nullable to Non-nullable

The code will now compile and give you desired results. However using the null coalescing operator in such scenarios, you can create clearer code than the equivalent if-else statement, as shown below:

image

In the code shown above, if ‘a’ has been assigned a non-null value, then this value will be assigned to the int b. However since the nullable type ‘a’ has been assigned null, the value to the right of the operator (??) i.e. zero will be assigned to b instead.

The value of b if printed, is 0.

 

Scenario 2 – Initializing instance fields in a Struct

You cannot declare instance field initializers in a Struct. The following piece of code:

image

gives a compilation error: cannot have instance field initializers in structs 

However using the Null coalescing operator, you can use a work-around as follows:

Struct Field Initializer

The value A can now be accessed and will return 1. Quite a handy technique using the Nullable type and the Null Coalescing operator!

There are some more ways the Null-coalescing operator can be used. I have covered some basic uses in my article Different Ways of using the C# Null Coalescing Operator.

Like any other feature, use it ‘only’ when required. It can greatly enhance your code, making it terse and pleasant to read!

I hope you liked the article and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Jason on Tuesday, August 2, 2011 11:30 AM
I found your first example a little misleading...

The reason you get an invalidoperationexception is that you are accessing a getter of an object which is null - a.Value. Where you illustrate the coalescing fix you use int b = a ?? 0. If you changed this to the original syntax int b = a.Value ?? 0 you would get the exact same exception.



Comment posted by Suprotim Agarwal on Tuesday, August 2, 2011 12:56 PM
Jason: I tried to show a cleaner and better way of writing that code and I did not mean to do a comparison here. The reason we get an exception is that the value (null) of Nullable<int> cannot be represented in an int. So you either do a cast or in the IF..ELSE, we assign a value that the int can represent.

However in case of a null coalescing operator, the code is a lot cleaner - If the nullable type contains a non-null value, assign it to the int. If not, assign the value of the right operand. Neat, easy to understand!

Sorry if the example was confusing for you.
Comment posted by Maarten on Wednesday, August 3, 2011 4:39 AM
No, Jason is right.
The reason an exception is thrown is because accessing the a.Value property will throw an exception.
In the first example, the int (b) is not set, the exception is thrown before that takes place.

For example 'string c = a.Value.ToString()' will still throw the same exception, it will not throw a NullReferenceException which it would do if you could access the a.Value property.
Comment posted by AnteSim on Thursday, August 4, 2011 1:58 AM
Its also handy for lazy initialisation:

    private object _myObject;
    public Object MyObject
    {
        get { return _myObject ?? ( _myObject = new object() ); }
    }
Comment posted by Steven Wexler on Thursday, May 15, 2014 10:55 PM
You may also be interested in NullSafe as explained by http://www.codeducky.org/10-utilities-c-developers-should-know-part-one/


foo.NullSafe(f => f.GetBar())
   .NullSafe(b => b.Baz)
   .NullSafe(b => b.SomeMethod(), ifNullReturn: "whatever you would return in the null case");

public static TResult NullSafe<TObj, TResult>(
   this TObj obj,
   Func<TObj, TResult> func,
   TResult ifNullReturn = default(TResult))
{
   return obj != null ? func(obj) : ifNullReturn;
}