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.