title: Dynamic constructor in C#
body: <p>I am trying to write a method <code>GetDynamicConstructor&lt;T&gt;</code> which will return, essentially, a smart constructor for the given class. It will accept an array of strings as parameters and parse them as the appropriate type (given existing constructor data).</p>
  
  <pre><code>public void Init()
  {
      DynamicConstructor&lt;MyClass&gt; ctor = GetDynamicConstructor&lt;MyClass&gt;();
      MyClass instance = ctor(new string[] { "123", "abc" }); // parse "123" as int
  }
  
  public delegate T DynamicConstructor&lt;T&gt;(string[] args);
  
  public DynamicConstructor&lt;T&gt; GetDynamicConstructor&lt;T&gt;()
  {
      ConstructorInfo originalCtor = typeof(T).GetConstructors().First();
  
      ParameterInfo[] paramsInfo = originalCtor.GetParameters();
  
      for (int i = 0; i &lt; paramsInfo.Length; i++) {
          Type paramType = paramsInfo[i].ParameterType;
  
          // This is as far as I got :D
      }
  
      return null;
  }
  
  public class MyClass
  {
      int n;
      string s;
  
      public MyClass(int n, string s)
      {
          this.n = n;
          this.s = s;
      }
  }
  </code></pre>
  
  <p>What I want, basically, is to construct from <code>MyClass</code> a method which looks like this.</p>
  
  <pre><code>public MyClass Example(string[] args)
  {
      return new MyClass(int.Parse(args[0]), args[1]);
  }
  </code></pre>
  
  <p>There will only be basic types here so I can count on a <code>Parse</code> existing for the types I might run into.</p>
  
  <p>How can I write the body of <code>GetDynamicConstructor&lt;T&gt;</code>?</p>