Monday, July 20, 2015

Null Conditional Operators

I cannot count the number of times that I've faced exception caused by running into a null. This then leads to code using the if{} blocks or using the short hand "?" on almost all of your variables.

In C# 6.0 specification a null conditional operator. The null conditional operator allows you to check for the instance of a null and replace a returned value or to return a value.

For example :

If you have a simple class such as a Person :

public class person
{

public string Name {get;set;}

public int Age {get; set;}

}

and you instantiate the class :

person me = new person();


then if you do something like

Console.Writeline(me.Name);


you'll get a null exception since the Name has not been instantiated. Often to overcome this specific problem we use constructors :

public class person
{

public string Name {get;set;}

public int Age {get; set;}

public person()
{
Name = "";
Age = 0;
}

}

The Null Conditional Operator now allows you to check for the null based on a shorthand, and this is how it would look in use:

Console.Writeline(me?.Name ?? "Empty Name");

So lets look at what this is doing, the first item to look at is "me?.Name" which is essentially checking the object me to see if it is null, if it is not null it will look at the Name property. The second part is '?? "Empty Name"' which is basically stating that if any part of the expression is null then use the string "Empty Name".

This shorthand example is very important and useful in order to make your program less verbose. For example in order to the above single line you would have had to do multiple if{} blocks (first to check that me is not null, and then the Name property is not null.





0 comments:

Post a Comment