Null Checking. Its necessary but also requires more code just to do straight forward tests. There have been many times I have thought “wouldn’t it be great if there was some way to check the object tree without have to write all these null checks.” There is a feature in C# 6 that makes this possible. In addition, it makes code a lot cleaner and easier read. This feature has been around for a bit now but its worth repeating since its such a nice concise feature. I figured I would write this up because I was looking at an older code bases that had all these null checks and was reminded that there is a much easier way.
Ever have code that looks like this:
if ( myObject != null && myObject.nestedProperty != null && myObject.nestedProperty.subProperty== null ){
//Do Something
}
A lot of code check to get the value of that subProperty. In C# 6 you can write something like
if ( myObject?.nestedProperty?.subProperty != null)Basically this is traversing the object tree and will return null if it hits something in the tree that is null. Pretty sweet! I have heard this called the Elvis Operator.
{
//Do Soemthing
}
Full list of new C# features can be found here.
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6#null-conditional-operators
Always a good idea to read these kind of lists just to so what new features can make code cleaner and easier.
