title: Null propagation in Expression Tree
body: <p>See sample code below. How can I modify it to handle null values, similar to how the <code>?.</code> operator works?</p>
  
  <pre><code>class Program
  {
      static LambdaExpression GetExpression(Expression&lt;Func&lt;string, string&gt;&gt; expr)
      {
          return expr;
      }
  
      static void Main(string[] args)
      {
          // I want to perform the following null propagation check
          // in the expression tree below.
          // (s as string)?.Replace("a", "o");
  
          var expr = GetExpression(t =&gt; t);
  
          var oldValue = Expression.Constant("a", typeof(string));
          var newValue = Expression.Constant("o", typeof(string));
          var mi = typeof(string).GetMethod(nameof(string.Replace), new[] { typeof(string), typeof(string) });
  
          var invoke = Expression.Invoke(expr, expr.Parameters);
          var call = Expression.Call(invoke, mi, oldValue, newValue);
          var lambda = Expression.Lambda(call, false, expr.Parameters);
  
          Console.WriteLine(lambda.Compile().DynamicInvoke("gaga"));
  
          // Should print empty line. Not throw!
          Console.WriteLine(lambda.Compile().DynamicInvoke(null));
      }
  }
  </code></pre>