One of the useful additions to the C# language in version 6 that I regularly use is the null-conditional operator. Checking for null is something that is regularly done, the new null-conditional operator helps to reduce the amount of code that you have to write.
Below is a simplified explanation of the null conditional operator:
The expression A?.B evaluates to B if the left operand 'A' is not null; otherwise, it evaluates to null.
Here’s a simple example of how it can be used.
public class Dog
{
public string Name { get; set; }
public int Age { get; set; }
public Toy FavouriteToy { get; set; }
}
Assume that d represents a dog. We can do the following.
var name = d?.Name;
var breed = d?.Breed;
The variable name
is a string. If d
is null, name
is null. If d
is not null, name
is the value of d.Name
.
The variable age
is an nullable int. If d
is null, age
is null. If d
is not null, age
is the value of d.Age
.
Consider the example above where the Dog
class contains a reference to the dog’s favourite toy. We can chain null-conditional operators to retrieve the favourite toy’s name.
var favouriteToy = d?.FavouriteToy?.Name;
This is roughly equivalent to
var favouriteToy = (d == null) ? null : (d.FavouriteToy == null) ? null : d.FavouriteToy.Name;
So we can see in this example the code becomes a lot cleaner.
Other usage scenarios
GetDog()?.FavouriteToy?.Name ?? "Dog needs a name";
private Func<Dog, bool> Walk;
Walk?.Invoke(dog)
var thing = new TFoo();
(thing as ICanDoSomething)?.DoSomething();