title: C# Expression Tree: Using TypeAs
body: <p>My first foray into writing an expression tree in c# is not going too well :). Here's the c# code I'm trying to duplicate</p>
  
  <pre><code>public static object Test&lt;S, D&gt;(S source, Func&lt;D, object&gt; selector )
      where S : class
      where D : class
  {
      D derived = source as D;
  
      object retVal = null;
  
      if( derived != null ) retVal = selector(derived);
  
      return retVal;
  }
  </code></pre>
  
  <p>Conceptually, this is intended to take an object and apply a selector to it to return a property of a derived class if the supplied object is of the derived class.</p>
  
  <p>Here's what I've got so far:</p>
  
  <pre><code>public static object OrderByDerivedProperty&lt;S&gt;( S source, Type derivedType, string fieldName )
  {
      ParameterExpression parameter = Expression.Parameter(typeof(S), "source");
      UnaryExpression typeAs = Expression.TypeAs(parameter, derivedType);
  
      ConstantExpression nullConst = Expression.Constant(null);
      BinaryExpression isNotNull = Expression.NotEqual(typeAs, nullConst);
  
      ParameterExpression varDest = Expression.Variable(derivedType, "varDest");
      ParameterExpression retVal = Expression.Variable(typeof(object), "retVal");
  
      BlockExpression block = Expression.Block(
          new[] { varDest, retVal },
          Expression.Assign(varDest, typeAs),
          Expression.Condition(
              isNotNull, 
              Expression.Assign(retVal, Expression.Property(varDest, fieldName)), 
              Expression.Assign(retVal, nullConst)
              ),
          retVal
      );
  
      LambdaExpression lambda = Expression.Lambda(block, new[] { parameter });
  
      return lambda.Compile().DynamicInvoke(source);
  }
  </code></pre>
  
  <p>I've used a somewhat different set of arguments here to simplify my expressions.</p>
  
  <p>The code works when derivedType is, in fact, a Type derived from S. However, if it isn't -- when I'm expecting the code to return retVal = null -- it blows up at the following line:</p>
  
  <pre><code>Expression.Assign(retVal, Expression.Property(varDest, fieldName)), 
  </code></pre>
  
  <p>complaining that fieldName is not a property of varDest. Which is correct in that case...but I was expecting the "if true" arm of the Condtional expression to not be evaluated if the test expression was false. That's clearly not the case.</p>
  
  <p>What I don't know about expression trees would fill (more than) a book. But if someone can point out where I'm going off the rails I'd appreciate it.</p>