title: Get Constructor Matching Parameters
body: <p>I have a method which takes in a constructor arguments as</p>
  
  <pre><code>Expression&lt;func&lt;T&gt;&gt;
  </code></pre>
  
  <p>thus declared as </p>
  
  <pre><code>object[] _constructorArgs = () =&gt; new MyClass("StringParam", 56, "ThirdParam");
  </code></pre>
  
  <p>I would instantiate this object as;</p>
  
  <pre><code>Activator.CreateInstance(typeof(MyClass), _constructorArgs);
  </code></pre>
  
  <p>Which works fine, but it's a bit slow.</p>
  
  <p>Is there a way I can gather the types Constructor based on the contents of _constructorArgs so I would be able to call </p>
  
  <pre><code>ConstructorInfo.Invoke(_constructorArgs);
  </code></pre>
  
  <p>?</p>
  
  <p>I know the Invoke is possible this way, it's just about finding the correct constructor based on the parameters in _constructorArgs.</p>
  
  <p><strong>Edit - For clarity</strong></p>
  
  <p>Apologies, I was very tired when I first asked this and should have given it more thought.</p>
  
  <p>What I am doing is the following;</p>
  
  <pre><code>    public object Create&lt;T&gt;(Expression&lt;Func&lt;T&gt;&gt; constructor)
      {
          //I didn't include this step in the original code
          var constructorArguments =
              (((NewExpression)constructor.Body).Arguments.Select(
                  argument =&gt; Expression.Lambda(argument).Compile().DynamicInvoke())).ToArray();
  
          object[] _args = constructorArguments;
  
          return Activator.CreateInstance(typeof(T), _args);
      }
  </code></pre>
  
  <p>However, if I do the following instead;</p>
  
  <pre><code>         ConstructorInfo c = type.GetConstructors().FirstOrDefault();
  
          //Get the types constructor
          return c.Invoke(_args);
  </code></pre>
  
  <p>I get better performance, I'm talking the first taking about 2800 milliseconds over a million iterations, using Invoke bringing that down to about 1000 milliseconds, thus 2.8 times faster.</p>
  
  <p>This will work great if the first constructor always matches the arguments given, but this won't always be the case. </p>
  
  <p>I want to know how I can get the correct ConstructorInfo based on arguments given.</p>