title: Builds a Delegate from MethodInfo?
body: <p>After googling and landing on SO and having read <a href="https://stackoverflow.com/questions/940675/getting-a-delegate-from-methodinfo">this other question</a></p>
  
  <blockquote>
    <p><strong>Is it possible to build a correct Delegate from a MethodInfo <em>if</em> you didn't know the number or types of parameters at compile time?</strong></p>
  </blockquote>
  
  <p>More on this: can this be done elegantly without the use of Reflection.Emit or type builders?</p>
  
  <p>This is sorta a bummer for me because Delegate.CreateDelegate requires me to specify the correct Delegate type as the first parameter or else it would throw exceptions or invoke an incorrect method.</p>
  
  <p>I'm building some ninja gears and this would helps a lot... Thanks!</p>
  
  <hr>
  
  <p><strong>Here's a generic solution:</strong></p>
  
  <pre><code>/// &lt;summary&gt;
  /// Builds a Delegate instance from the supplied MethodInfo object and a target to invoke against.
  /// &lt;/summary&gt;
  public static Delegate ToDelegate(MethodInfo mi, object target)
  {
      if (mi == null) throw new ArgumentNullException("mi");
  
      Type delegateType;
  
      var typeArgs = mi.GetParameters()
          .Select(p =&gt; p.ParameterType)
          .ToList();
  
      // builds a delegate type
      if (mi.ReturnType == typeof(void)) {
          delegateType = Expression.GetActionType(typeArgs.ToArray());
  
      } else {
          typeArgs.Add(mi.ReturnType);
          delegateType = Expression.GetFuncType(typeArgs.ToArray());
      }
  
      // creates a binded delegate if target is supplied
      var result = (target == null)
          ? Delegate.CreateDelegate(delegateType, mi)
          : Delegate.CreateDelegate(delegateType, target, mi);
  
      return result;
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Note</strong>: I am building a Silverlight application that would replace a built-years-ago javascript application in which I have multiple Javascript interfaces that calls into the same Silverlight [ScriptableMember] method.</p>
  
  <p>All those legacy JS interfaces need to be supported as well as new interface for accessing new features, so something that automatically setups the JS interface and "delegates" the call to the right Silverlight method would helps speed up work a lot.</p>
  
  <p>I can't post code here, so that's the summary.</p>