/// <summary>Indexed properties create additional issues when the possibility of null is involved.</summary> public string GetIndexedMember_OldWay(InterestingClass src) { if (src == null) return null; if (src.Collection == null) return null; if (src.Collection[0] == null) return null; return src.Collection[0].FirstName; }
/// <summary>NEW WAY: Null Conditionals operate on Indexed properties.</summary> public string GetIndexedMember_NewWay(InterestingClass src) { // In this case, src is checked for null, // Then Collection property is checked, // Then the first member of the collection is checked // Finally returning the desired property return src?.Collection?[0]?.FirstName; }
/// <summary>Linq function FirstOrDefault benefits from null conditional operator, as for reference types, first or default /// return null if no member is found.</summary> public string GetLinqMemberUsingNull() { InterestingClass ic = new InterestingClass(); ic.Collection = new List<InterestingMemberClass>(); // In the following line, an object is initialized using named arguments. ic.Collection.Add(new InterestingMemberClass() { FirstName = "Jack", LastName = "Skellington" }); // In this line, the direct call to the constructor, using (), is omitted and the object is initialized. // The call to the default constructor is automatically invoked. ic.Collection.Add(new InterestingMemberClass { FirstName = "Sally", LastName = "Doll" }); return ic.Collection.FirstOrDefault(m => m.FirstName == "Jack")?.FirstName; }
/// <summary>NEW WAY: Each member is checked for null, and short-circuits and returns null if the member to the left of the ?. operator is null.</summary> public string GetName_NewWay(InterestingClass src) { return src?.Member?.LastName; }
/// <summary>OLD WAY: Each member class needs to be checked for null before accessing additional members.</summary> public string GetName_OldWay(InterestingClass src) { if (src == null) return null; if (src.Member == null) return null; if (src.Member.FirstName == null || src.Member.LastName == null) return null; return src.Member.LastName; }