Null Conditional Operator in C# 6.0

Introduction:

In this article I am going to explain about one of the new feature introduced with C# 6.0 – Null Conditional Operator.

Explanation:

Null reference is one of the common exception which normally faced by most of the developers if you didn’t handled by adding proper checking for null values in code.

To resolve this null reference exception till now what we did was to add proper check condition for null values in code like given below

string firstname = null;
//Check if Firstname is null or not 
if(firstname != null)
{
     string res = firstname.Substring(0, 4);
}

Even though above code will works fine, we need to add additional code like if condition and all to safeguard the code from null reference exception. Wouldn’t it be nice if you have a single line of code which actually checks for null condition and the handles it.

With C# 6.0 they introduced a new operator called Null Conditional Operator (?). This will handles the above line of code in a single statement like given below

string firstname = null;
//Handle the null case using the operator(?) this wont throw null reference exception
string res = firstname?.Substring(0, 4);

Internally what the null conditional operator do is it will check for null before calling the following methods and if there is any null value the code execution will won’t proceed further and return the null value which subsequently stop the null reference exception from occurring.

Ex: In below code

string res = firstname?.Substring(0, 4);

Null conditional operator first check for null values in firstname and it will call the following method Substring method only if firstname is not null.

A word of caution while using null conditional operator is that you need to ensure that the variable you are assigning the result will be of nullable type

Ex:

The below code will throw an exception

DataTable dttable = new DataTable();
dttable = null;
int rowcount = dttable?.Rows.Count;

You need to make it nullable using nullableint to resolve the issue

DataTable dttable = new DataTable();
dttable = null;
int? rowcount = dttable?.Rows.Count;
Advertisements

, , , ,

  1. Leave a comment

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

%d bloggers like this: