I have been looking around finding the best possible option for handling null objects in calling a method (or method chain).
It is our common practice to check with if condition:
if ( customObject != null ) {
customObject.callMe();
}
Which can be further improved by using extension methods:
Program customObject = null;
if (customObject.NotNull()) {
customObject.CallMe();
}
public static bool NotNull(this object o) {
return o == null;
}
PLEASE NOTE: I normally ignore ! from my programming practice. Hence it is wise to say that for me extension methods are good to go.
However, it becomes very complicated in dealing with when the Method chain is involved.
customObject.CallMe().CallMe2() ex...
How you do think it can be handled in C#, so that the CallMe
is called only if customObject
is not null and CallMe2
is called only if CallMe
returns non null object.
Of course I can use If conditions or ternary operator. However, I would want to know if vNext, C#5.0 has some thing to offer.
In the upcoming C# 6 (vNext) has the ?.
operator (Null Conditional Operator) which easily allow you to chain null reference checks for every nested property.
An example of this would be:
int? first = customers?.[0].Orders?.Count();
This was a requested feature in the Visual Studio UserVoice site
You can see the status for all the new language features for C# 6.0 on the Codeplex site for Roslyn: