1 linear, beautiful and clean way to assign value if null in C #?

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.

+6
source share
1 answer

What about the zero propagation operator that 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 sets the default value if any of them is null.

I expanded this function by creating an extension method that also checks for an empty one:

 string result = (myParent?.objProperty?.strProperty) .IfNullOrEmpty("default string value if strObjProperty is null"); 

Where IfNullOrEmpty true:

 public static string IfNullOrEmpty(this string s, string defaultValue) { return !string.IsNullOrEmpty(s) ? s : defaultValue); } 
+11
source

All Articles