Who hasn’t heard of NullReferenceException? I am sure all of us. To avoid this, we use enormous If conditions for null checking.
Let us consider the code listing below. We have a list of “Author”. Before fetching the Name of a particular Author, we are performing the null checking in if statement. If we do not do that, a NullReferenceException will be thrown.
static void Main(string[] args)
{
Author author = null;
List<Author> lstAuthors = new List<Author>();
lstAuthors.Add(author);
foreach(var a in lstAuthors)
{
if (a != null)
{
var name = a.Name;
WriteLine(name);
}
}
ReadKey(true);
}
In C# 6.0, we can avoid if statements by using Null Conditional Operators.
We can rewrite the above code for the null checking as shown in the listing below:
static void Main(string[] args)
{
Author author = null;
List<Author> lstAuthors = new List<Author>();
lstAuthors.Add(author);
foreach(var a in lstAuthors)
{
var name = a?.Name;
Write(name);
}
ReadKey(true);
}
In C#6.0 it is very easy to do the null reference checking using the null conditional operator (?). I am sure this feature would be wildly used, hence it’s one of my favorite features of C# 6.0.
0 comments :
Post a Comment