In C # 5 and below, as indicated in other answers, you need to create something yourself. Instead of using the Extension method, like others, an assistant is used here, which we call NN, since we use its LOT, especially in Razor.
public static TValue N<TParent, TValue>(TParent o, Func<TParent, TValue> accessor, TValue defaultValue) { if (o == null) return defaultValue; return accessor(o); } /// <summary> /// Guarantees return of null or value, given a prop you want to access, even if the parent in the first argument /// is null (instead of throwing). /// /// Usage: /// /// NN.N(myObjThatCouldBeNull, o => o.ChildPropIWant) /// </summary> /// <returns>The value of the prop. Null if the object is null, or if the child prop is null.</returns> public static TValue N<TParent, TValue>(TParent o, Func<TParent, TValue> accessor) where TValue : class { return NN.N(o, accessor, null); }
We actually use several helpers depending on the desired behavior when zero occurs ; for example, you can access the int property and want 0. Full code in the associated Gist.
In C # 6, you can use the null property union operator:
myObjThatCouldBeNull?.ChildPropIWant
More on this:
https://roslyn.codeplex.com/discussions/540883
Chris moschini
source share