Is there a cleaner way to write null propagation in the earlier version of C#? -
i have class.
class property { public int? propertyid { get; set; } }
i have following statement wrote in c# 6.0
property p = null; var id = p?.propertyid.getvalueordefault() ?? 0;
turns out null propagation doesn't work in c# 5.0. rewrote as:
int id = 0; if (propertybyaddress != null && propertybyaddress.propertyid != null) { id = p.propertyid.value; }
it seems unnecessarily wordy. there cleaner way in c# 5.0?
you can still use getvalueordefault in c# 5.0, yes null check necessary.
int id = 0; property p = null; if (p != null) id = p.propertyid.getvalueordefault();
you make extension method pointed out camilo, if feel that's "cleaner".
propertyextensions.cs
public static int getpropertyidvalueordefault(this property p) { if (p != null) return p.propertyid.getvalueordefault(); return 0; }
usage:
property p = null; var id = p.getpropertyidvalueordefault();
Comments
Post a Comment