Before you rush, think about ??? zero coalescing operator:
string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null";
The problem is when myParent or objProperty is NULL, then it will throw an exception before it even reaches the strProperty evaluation.
To avoid the following additional null checks:
if (myParent != null) { if (objProperty!= null) { string result = myParent.objProperty.strProperty ?? "default string value if strObjProperty is null"; } }
I usually use something like this:
string result = ((myParent ?? new ParentClass()) .objProperty ?? new ObjPropertyClass()) .strProperty ?? "default string value if strObjProperty is null";
So, if an object is null, it creates a new one to be able to access the property.
It is not very clean.
I would like something like "???" Operator:
string result = (myParent.objProperty.strProperty) ??? "default string value if strObjProperty is null";
... that will withstand all the βzeroβ from within the parenthesis to return the default value instead.
Thanks for your advice.
source share