title: How to use Expression Tree to safely access path of nullable objects?
body: <p>When I get deserialized XML result into xsd-generated tree of objects and want to use some deep object inside that tree a.b.c.d.e.f, it will give me exception if any node on that query path is missing.</p>
  
  <pre><code>if(a.b.c.d.e.f != null)
      Console.Write("ok");
  </code></pre>
  
  <p>I want to avoid checking for null for each level like this:</p>
  
  <pre><code>if(a != null)
  if(a.b != null)
  if(a.b.c != null)
  if(a.b.c.d != null)
  if(a.b.c.d.e != null)
  if(a.b.c.d.e.f != null)
      Console.Write("ok");
  </code></pre>
  
  <p>First solution is to implement Get extension method that allows this:</p>
  
  <pre><code>if(a.Get(o=&gt;o.b).Get(o=&gt;o.c).Get(o=&gt;o.d).Get(o=&gt;o.e).Get(o=&gt;o.f) != null)
      Console.Write("ok");
  </code></pre>
  
  <p>Second solution is to implement Get(string) extension method and use reflection to get result looking like this:</p>
  
  <pre><code>if(a.Get("b.c.d.e.f") != null)
      Console.Write("ok");
  </code></pre>
  
  <p>Third solution, could be to implement ExpandoObject and use dynamic type to get result looking like this:</p>
  
  <pre><code>dynamic da = new SafeExpando(a);
  if(da.b.c.d.e.f != null)
      Console.Write("ok");
  </code></pre>
  
  <p>But last 2 solutions do not give benefits of strong typing and IntelliSense.</p>
  
  <p>I think the best could be fourth solution that can be implemented with Expression Trees:</p>
  
  <pre><code>if(Get(a.b.c.d.e.f) != null)
      Console.Write("ok");
  </code></pre>
  
  <p>or</p>
  
  <pre><code>if(a.Get(a=&gt;a.b.c.d.e.f) != null)
      Console.Write("ok");
  </code></pre>
  
  <p>I already implemented 1st and 2nd solutions.</p>
  
  <p>Here is how 1st solution looks like:</p>
  
  <pre><code>[DebuggerStepThrough]
  public static To Get&lt;From,To&gt;(this From @this, Func&lt;From,To&gt; get)
  {
      var ret = default(To);
      if(@this != null &amp;&amp; !@this.Equals(default(From)))
          ret = get(@this);
  
      if(ret == null &amp;&amp; typeof(To).IsArray)
          ret = (To)Activator.CreateInstance(typeof(To), 0);
  
      return ret;
  }
  </code></pre>
  
  <p>How to implement 4th solution if possible ?</p>
  
  <p>Also it would be interesting to see how to implement 3rd solution if possible.</p>