C# 6: We don’t care if it’s null

Lets touch on another epic little feature of C# 6, the null operator.

As always with my blog posts, I want to keep things simple. The null operator avoids the if(thing!=null) checks that often clutter our code. Often, we want to set a property or value if an object instance is NOT null. This usually results in us wrapping the dereference statement in a big if condition, when this sometimes is overkill.

C#6 has a new feature that helps you cut down on the amount of code you have to write. Lets have a look

For example, a typical senario would be something like this:

We have to get something from the Database and then set a Property (Name in the example) to a property of the object we got back.


public string Name{ get; set; }

public void SetNameFromItem(int itemId)
{
   // Try get item from the database
   Item item = ItemRepository.GetItem(itemId);

   // Check if item is not null to avoid Null Reference Exception
   if(item!=null)
   {
      // Safely dereference object and set value
      Name = item.Name;
   }

   // Unsafely dereference object - would throw Null Ref. Exception if item was null
   Name = item.Name;
}

 

OK, lets write that again using C#6’s null operator (I have shown a few variations):


public string Name{ get; set; }

public void SetNameFromItem(int itemId)
{
   // Try get item from the database
   Item item = ItemRepository.GetItem(itemId);

   //// Safely dereference object with no default (will return null if item is null)
   Name = item?.Name;
   //// Safely dereference object with default value 🙂
   Name = item?.Name ?? "Default value if item is null";
   //// Safely chain method calls
   Name = item?.Name.Trim(); // Trim() will not be called if item is null - avoids Null Ref. Exception
}

In short, to dereference an object that might be null, use “?.” instead of “.” and then specify the default value (if the object is null) using the “??” operators.

Disclaimer: This is not a catch-all for whenever you need to dereference objects. Use it when it makes sense!

Happy null-operating!

More info: https://msdn.microsoft.com/en-us/magazine/dn802602.aspx

Advertisements

One Comment Add yours

  1. Mr. Gaia says:

    PS, I think MS also refers to it as the “Elvis operator” … 🙂

    Like

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