65.9K
CodeProject is changing. Read more.
Home

New Features in C# 6.0 – Null Conditional Operator

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.75/5 (3 votes)

Oct 2, 2014

CPOL

1 min read

viewsIcon

27625

This post is about null conditional operator in C#.

This is blog post series about new features coming in the next version of C# 6.0. The first post is about null conditional operator.

The NullReferenceException is a nightmare for any developer specially for developers with not much experience. Almost every created object must be checked against null value before we call some of its members. For example, assume we have the following code sample:

class Record
{
 public Person Person  {get;set;}
 public Activity Activity  {get;set;}
}
public static PrintReport(Record rec)
{
  string str="";
   if(rec!=null && rec.Person!=null && rec.Activity!=null)
   {
     str= string.Format("Record for {0} {1} took {2} sec.", 
          rec.Person.FirstName??"",rec.Person.SurName??"", rec.Activity.Duration);
     Console.WriteLine(str);
   }

  return ;
}

We have to be sure that all of the objects are nonnull, otherwise we get NullReferenceException.

The next version of C# provides Null-Conditional operation which reduces the code significantly.

So, in the next version of C#, we can write Print method like the following without fear of NullReferenceException.

public static PrintReport(Record rec)
{
  var str= string.Format("Record for {0} {1} took {2} sec.", 
           rec?.Person?.FirstName??"",rec?.Person?.SurName??"", rec?.Activity?.Duration);
     Console.WriteLine(str);

  return;
}

As we can see, ‘?’ is a very handy way to reduce our number of if statements in the code. The Null-Conditional operation is more interesting when it is used in combination of ?? null operator. For example:

 string name=records?[0].Person?.Name??"n/a";

The code listing above checks if the array of records not empty or null, then checks if the Person object is not null. At the end, null operator (??) in case of null value of the Name property member of the Person object put default string “n/a”.

For this operation, regularly we need to check several expressions against null value.
Happy programming!

Filed under: .NET, C#, CodeProject
Tagged: .NET, C#, C# 6.0, CodeProject