.NET Fiddle
As indicated, is there a plan for C # 6.0 to implement the operator ? to facilitate this process. If you cannot wait, I would suggest using a lambda expression and a simple helper function to solve this problem.
public E NestedProperty<T,E>(T Parent, Func<T,E> Path, E IfNullOrEmpty = default(E)) { try { return Path(Parent); } catch { return IfNullOrEmpty; } }
This can be used int value = NestedProperty<First,int>(blank,f => f.Second.Third.id); as shown in the demo below
program
public class Program { public void Main() { First blank = new First(); First populated = new First(true);
simple demo structure
public class First { public Second Second { get; set; } public int id { get; set; } public First(){} public First(bool init) { this.id = 1; this.Second = new Second(); } } public class Second { public Third Third { get; set; } public int id { get; set; } public Second() { this.id = 1; this.Third = new Third(); } } public class Third { public int id { get; set; } public Third() { this.id = 1; } }
Travis j
source share