title: C# How to Build an Expression<Func<T, U>> for each Property of an Object?
body: <p>I have a class <code>FormBuilder&lt;TObject&gt;</code> which has a method <code>Property&lt;TProperty&gt;(Expression&lt;Func&lt;TObject, TProperty&gt;&gt; expression)</code>. In the constructor I would like to invoke the method after getting all of the properties of <code>TObject</code>. How can I go about doing that? The code I have now, adapted from other SO answers, just throws errors, and I'm not sure how to resolve them. This is what I have so far:</p>
  
  <pre><code>public abstract class FormBuilder&lt;TObject&gt; :
      FormBuilder {
      public FormBuilder() {
          //  REPLICATE: Property(p =&gt; p.NAME);
  
          var method = this.GetType().GetMethod("Property");
          var properties = typeof(TObject).GetProperties();
  
          var objectType = typeof(TObject);
  
          foreach (var p in properties) {
              var propertyType = p.GetType();
  
              var parameter = Expression.Parameter(propertyType, "p");
              var property = Expression.Property(parameter, p.Name);
              var @delegate = typeof(Func&lt;,&gt;).MakeGenericType(objectType, propertyType);
  
              //  throws: ParameterExpression of type 'System.Reflection.RuntimePropertyInfo'
              //  cannot be used for delegate parameter of type 'UserQuery+Command'
              var expression = Expression.Lambda(@delegate, property, new[] { parameter });
  
              //  method.MakeGenericMethod(parameter).Invoke(this, new[] { property });
          }
      }
  
      public FormPropertyBuilder&lt;TProperty&gt; Property&lt;TProperty&gt;(
          Expression&lt;Func&lt;TObject, TProperty&gt;&gt; expression) {
          var member = (expression.Body as MemberExpression).Member;
          var builder = new FormPropertyBuilder&lt;TProperty&gt;(member.Name);
  
          Properties.Add(builder);
  
          return builder;
      }
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <pre><code>public sealed class CommandFormBuilder :
      FormBuilder&lt;Command&gt; {
      public CommandFormBuilder() {
          Property(
              p =&gt; p.SourceOfLoss).HasLabel("Source of Loss");
      }
  }
  </code></pre>
  
  <p>This is how I would normally invoke the method, but I need to invoke it immediately upon construction for each property.</p>
  
  <p>My end goal is to simply seed all the properties through the method, and do further configuration on them later on if necessary. I appreciate any help!</p>