James Michael Hare

...hare-brained ideas from the realm of software development...
posts - 166 , comments - 1474 , trackbacks - 0

My Links

News

Welcome to my blog! I'm a Sr. Software Development Engineer in the Seattle area, who has been performing C++/C#/Java development for over 20 years, but have definitely learned that there is always more to learn!

All thoughts and opinions expressed in my blog and my comments are my own and do not represent the thoughts of my employer.

Blogs I Read

Follow BlkRabbitCoder on Twitter

Tag Cloud

Archives

Post Categories

.NET

CSharp

Little Wonders

Little Wonders

vNext

C#/.NET Little Wonders: Null Conditional Operator in C# 6

Once again, in this series of posts I look at the parts of the .NET Framework that may seem trivial, but can help improve your code by making it easier to write and maintain. The index of all my past little wonders posts can be found here.

Visual Studio 2015 is on the horizon!  In fact, some of you may already have played with the preview and seen some of the many neat new things to come – both in the IDE and in the C# language.

Note: All of the C# 6 features mentioned are current with the latest CTP of VS2015 as of the time of this writing.  The syntax and exact feature behaviors may be subject to change in the final released version.

Too many layers of null checks!

How many times have you had to consume a web service, and that web service has had many layers of nested objects, each of which can potentially be null

Often times, to be safe, this makes us end up having to write logic like this:

   1: var response = someProxy.SomeWebMethod();
   2:  
   3: // so many layers, so many potential nulls...
   4: if (response != null && response.Results != null && response.Results.Status == Status.Success)
   5: {
   6:     Console.WriteLine("We were successful!");
   7: }

And this is just a status buried down two layers, imagine if the model was four, five, or six layers deep!

This happens a lot in C# (and Java) where at any step along the way of a deeply-nested model, you could encounter a null.  Indeed it would be nice to be able to have an option to cascade the null down the chain if there’s a null along the way.

Now, we get this new feature in C# 6, the null conditional operator.  This operator does exactly what we’re talking about: if the left side of the operator is null, it cascades a null of the resulting type to the right. 

In short, if you replace your “.” with the null conditional operator “?. it will cascade the null down the line:

   1: var response = someProxy.SomeWebMethod();
   2:  
   3: // so much better!
   4: if (response?.Results?.Status == Status.Success)
   5: {
   6:     Console.WriteLine("We were successful!");
   7: }

So, if response is null, or if response.Results is null, then the result will be a null matching the return type of Status.  If not, you will get the actual value of Status.

Now, notice that we have “?.” in there twice, this is because we need to use the “?.” everywhere that we want to cascade the null otherwise a null will throw as expected.

For example, consider the following four similar conditionals:

   1: // #1
   2: if (response.Results.Status == Status.Success) { }
   3:  
   4: // #2
   5: if (response?.Results.Status == Status.Success) { }
   6:  
   7: // #3
   8: if (response.Results?.Status == Status.Success) { }
   9:  
  10: // #4
  11: if (response?.Results?.Status == Status.Success) { }

Let’s look at each of these in turn:

  1. The first will throw if either response or response.Results are null 
  2. The second will throw only if response.Results is null, but will cascade if response is null
  3. The third will throw if response is null, but will cascade if response.Results is null
  4. The fourth will cascade if either response or response.Results are null

Most of the time, unless you know an element cannot be null in a chain (like if it’s a struct), you’ll want to continue to cascade down an identifier chain once you start.

What does null-cascading with a value type result do?

Let’s say that Results has a Count field that evaluates to an int, what would happen if we did this?

   1: // what is the type of the LHS?
   2: if (response?.Results?.Count > 0)
   3: {
   4:     Console.WriteLine("We got data!");
   5: }

The above does compile.  This is because C# is smart enough to realize that the end result of the chain is a value type, so it converts it to a Nullable<int> instead.  This means we may be comparing null to zero.  However, if you study the way nullable math works in C# (much like in SQL) you’ll find that null > 0 is false (incidentally so is null < 0).  For more details, see this post on Nullable Math Doesn’t Always Add Up.

Or, let’s do this instead:

   1: // won't compile, will complain that can't implicitly convert
   2: // Nullable<int> to int
   3: int count = response?.Results?.Count;

You’ll see right away that C# considers the end result of that identifier chain to be Nullalble<int> (also referred to as int?) instead of int.

Want a default other than null? 

What if you want to cascade the null, but want to use another default value instead.  For example, take the Count expression above where it gave us a Nullable<int> that can cause some interesting math comparisons if the value is null, it would be better if we could cascade to something like zero.

Well, you can combine the null conditional operator with the null-coalescing operator (??) to provide a different default on null.

   1: // This will compile, if the expression evaluate to null then 0 will be used.
   2: int count = response?.Results?.Count ?? 0;

Indeed, notice that now we can type the value of count to int since null is no longer an option.

What if we’re dealing with an indexer property?

So, you may have noticed we’ve been dealing directly with members accessed using the dot (“.”) operator, what happens if we want to use an indexer property (“[]”)?

For example, let’s say that Results contained a List<Address> called Addresses. And List<T> has an indexer property.

We don’t want to have to go back to:

   1: // notice the [...] indexer on addresses
   2: if (response != null && response.Results != null && response.Results.Addresses != null
   3:     && response.Results.Addresses[0] != null && response.Results.Addresses[0].Zip == "63368")
   4: {
   5:     Console.WriteLine("Are we neighbors?");
   6: }

Notice the indexer on Addresses, so we can’t use “?.“ because indexers use a different syntax than fields, properties, and methods.  Fortunately, C# provides a null conditional form of the indexer operator “?[]” which works just like the standard member-access null conditional operator, but for indexers instead.

So now, we can write:

   1: // Again, much cleaner...
   2: if (response?.Results?.Addresses?[0]?.Zip == "63368")
   3: {
   4:     Console.WriteLine("Are we neighbors?");
   5: }

With this, if response, response.Results, response.Results.Addresses, or response.Results.Addresses[0] are null, we will coalesce a null as the final result.

But wait, it works for more than just fields and properties…

The null conditional operator is not simply for fields and properties, it can be used for method calls as well.  Once again, if the identifier chain on the left evaluates to null the method will not be called and a null matching the return type (if any) will be cascaded along.

For example, how often do you have code like this:

   1: if (x != null)
   2: {
   3:     x.Dispose();
   4: }

This is a fairly common occurrence, we want to call a function if the instance is not null, but it takes 4 lines of code to write that (assuming we do our full set of curlies).

Now, however, this can be simplified to one line:

   1: // a great one-liner!
   2: x?.Dispose();

Much cleaner!  Especially if you are doing a lot of these kind of statements in a larger cleanup operation; just imagine the lines you will save!

And what about processing events?  Those of you who have done any event raising know that there’s a standard pattern for raising an event where you take a copy of the handler, and then check the copy for null.  This is so that the value of the handler doesn’t change between the time you check and the time you invoke it.  We don’t want to lock the invocation, because that could be a very expensive lock if the subscribers do anything heavy.

   1: // to avoid locking, yet be thread-safe, must make a copy of the delegate
   2: // and then invoke the copy.  
   3: var copy = OnMyEvent;
   4: if (copy != null)
   5: {
   6:     copy(this, new EventArgs());
   7: }

For more details on this pattern, see Safely and Efficiently Raising Events

Now with the null conditional operator, we can do this instead:

   1: // again, reduced to a great one-liner:
   2: OnMyEvent?.Invoke(this, new EventArgs());
So, the ?. will evaluate first and make a copy of the reference (hence satisfying the copy pattern) and then based on whether that is null or not, it will invoke the delegate.

Summary

The null conditional operator is a great code-reducer to eliminate a lot of very verbose null-checking logic where cascading makes sense.  Keep in mind that a null-conditional chain that results in a value type will create a Nullable<T> instead, and particularly pay attention when you try to perform arithmetic or logical comparisons versus null.

Thanks for reading my Little Wonders of C# 6 series, I’ll be back soon with more Little Wonders and Little Puzzlers in the weeks to come.

Print | posted on Friday, June 5, 2015 12:26 AM |

Feedback

Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

I may be wrong but in your example #2:
if (response?.Results.Status == Status.Success) { }

if response is null, it won't cascade successfully as response?.Results will be null, therefore it will throw on fetching Status...

Or maybe I'm missing something
6/5/2015 4:49 AM | Wizou
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

Ok my bad
According to https://msdn.microsoft.com/en-us/library/dn986595%28v=vs.140%29.aspx
<< the null-condition operators are short-circuiting. If one operation in a chain of conditional member access and index operation returns null, then the rest of the chain’s execution stops >>
6/5/2015 4:52 AM | Wizou
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

Very handy feature! Just don't use it to break the Law of Demeter though ;)
6/5/2015 8:55 AM | Jeffrey Bridgman
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

@Wizou: Yes, I should have done a better job of explaining that the ?. doesn't just cascade the null to the next step, it cascades it short-cuts to be a null of the end result type.
6/5/2015 12:53 PM | James Michael Hare
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

Thank you for sharing.
http://madakotania.blog.fc2.com/blog-entry-3.html
6/5/2016 7:47 PM | selly
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

good post with useful information. http://kaelaevi.blog.fc2.com/blog-entry-3.html
6/5/2016 7:49 PM | laeci
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

"When it's null, then null. When it's not, then dot." - Mads
10/3/2016 7:22 PM | Vince Panuccio
Gravatar

# re: C#/.NET Little Wonders: Null Conditional Operator in C# 6

Great post! thank you for sharing..
https://wanitacantik17.wordpress.com/
3/6/2017 7:43 AM | oliver
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: