Visual Studio 2015: C# 6.0 Null-conditional Operator

NullReference exception is one of the main exceptions most of the code blocks return. For handling the same, we will verify most of the object is null or not before accessing the properties or elements of the object.

if (emps != null)
Console.WriteLine(“Number of Employees {0} “, emps.Count());

C# 6 introduced a new operator to handle the null verification. We can re-write the above statement as

Console.WriteLine(“Number of Employees {0} “, emps?.Count());

If the emps object is null, then return null; otherwise return the count of elements. If you want to return 0 in case of null, then the statement looks like

Console.WriteLine(“Number of Employees {0} “, emps?.Count()??0);

We can use the new null-conditional operator with chain statements like

Console.WriteLine(“Order Count {0} “, products?[0].Orders?.Count());

Above statement get the first product, if the products collection is not null and get the count of orders, if there is any orders exists. Otherwise, it returns null.

About ambilykk

I am a Technology Evangelist on Microsoft Technologies. I am carrying the passion on Microsoft technologies specifically on web technologies such as ASP .Net and Ajax. My interests also include Azure and Visual Studio. Technology adoption and learning is my key strength and technology sharing is my passion.
This entry was posted in C#, Visual Studio 2015 and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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 )

Connecting to %s