Click here to Skip to main content
15,886,689 members
Articles / Programming Languages / C#

New Features in C# 6.0 – Null Conditional Operator

Rate me:
Please Sign up or sign in to vote.
3.75/5 (3 votes)
2 Oct 2014CPOL1 min read 27.1K   9   4
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:

C#
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.

C#
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:

C#
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Bosnia and Herzegovina Bosnia and Herzegovina
Bahrudin Hrnjica holds a Ph.D. degree in Technical Science/Engineering from University in Bihać.
Besides teaching at University, he is in the software industry for more than two decades, focusing on development technologies e.g. .NET, Visual Studio, Desktop/Web/Cloud solutions.

He works on the development and application of different ML algorithms. In the development of ML-oriented solutions and modeling, he has more than 10 years of experience. His field of interest is also the development of predictive models with the ML.NET and Keras, but also actively develop two ML-based .NET open source projects: GPdotNET-genetic programming tool and ANNdotNET - deep learning tool on .NET platform. He works in multidisciplinary teams with the mission of optimizing and selecting the ML algorithms to build ML models.

He is the author of several books, and many online articles, writes a blog at http://bhrnjica.net, regularly holds lectures at local and regional conferences, User groups and Code Camp gatherings, and is also the founder of the Bihac Developer Meetup Group. Microsoft recognizes his work and awarded him with the prestigious Microsoft MVP title for the first time in 2011, which he still holds today.

Comments and Discussions

 
QuestionNice to see your approach but improvements are needed Pin
Jon "Greg"ory Rothlander28-Aug-15 8:21
professionalJon "Greg"ory Rothlander28-Aug-15 8:21 
Questionvery nice article! Pin
kau8118112-Jan-15 22:20
kau8118112-Jan-15 22:20 
QuestionLMGTFY Pin
Thornik3-Oct-14 6:40
Thornik3-Oct-14 6:40 
AnswerRe: LMGTFY Pin
kau8118112-Jan-15 22:11
kau8118112-Jan-15 22:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.