New Features in C# 6.0 - Null-Conditional Operator

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 night mare for any developer specially for developer with not much experience. Almost every created object must be check against null value before we call some of its member. 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 object are nonnull, otherwize we get NullReferenceException.

The next version of C# is provide Null-Conditional operation which reduce 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 that '?' is very handy way to reduce our number of if statements in the code. The Null-Conditional operation is more interesting when 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 agains null value.
Happy programming.

 


Posted Oct 01 2014, 09:47 PM by Bahrudin
developers.de is a .Net Community Blog powered by daenet GmbH.