Reputation: 183
Before you rush to think about the ?? null coalescing operator:
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
The problem here is when whether myParent or objProperty are null, then it will throw an exception before even reaching the evaluation of strProperty.
To avoid the following extra null checkings:
if (myParent != null)
{
if (objProperty!= null)
{
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
}
}
I generally use something like this:
string result = ((myParent ?? new ParentClass())
.objProperty ?? new ObjPropertyClass())
.strProperty ?? "default string value if strObjProperty is null";
So if the object is null then it creates a new one only to be able to access the property.
Which is not very clean.
I would like something like a '???' operator:
string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";
... which would survive whatever "null" from inside the parenthesis to return the default value instead.
Thanks for your tips.
Upvotes: 6
Views: 164
Reputation: 156948
What about the null propagation operator, which comes with C# 6?
string result = (myParent?.objProperty?.strProperty)
?? "default string value if strObjProperty is null";
It checks myParent
, objProperty
and strProperty
for null and will assign the default value if any of them is null.
I have extended this feature by creating a extension method that checks for empty too:
string result = (myParent?.objProperty?.strProperty)
.IfNullOrEmpty("default string value if strObjProperty is null");
Where IfNullOrEmpty
is just:
public static string IfNullOrEmpty(this string s, string defaultValue)
{
return !string.IsNullOrEmpty(s) ? s : defaultValue);
}
Upvotes: 10