title: Getting a delegate from methodinfo
body: <p>I have a drop down list that is populated by inspecting a class's methods and including those that match a specific signature. The problem is in taking the selected item from the list and getting the delegate to call that method in the class. The first method works, but I cannot figure out part of the second.</p>
  
  <p>For example,</p>
  
  <pre><code>public delegate void MyDelegate(MyState state);
  
  public static MyDelegate GetMyDelegateFromString(string methodName)
  {
      switch (methodName)
      {
          case "CallMethodOne":
              return MyFunctionsClass.CallMethodOne;
          case "CallMethodTwo":
              return MyFunctionsClass.CallMethodTwo;
          default:
              return MyFunctionsClass.CallMethodOne;
      }
  }
  
  public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
  {
      MyDelegate function = MyFunctionsClass.CallMethodOne;
  
      Type inf = typeof(MyFunctionsClass);
      foreach (var method in inf.GetMethods())
      {
          if (method.Name == methodName)
          {
              //function = method;
              //how do I get the function to call?
          }
      }
  
      return function;
  }
  </code></pre>
  
  <p>How do I get the commented out section of the second method to work? How do I cast the <code>MethodInfo</code> into the delegate?</p>
  
  <p>Thanks!</p>
  
  <p><strong>Edit: Here is the working solution.</strong></p>
  
  <pre><code>public static MyDelegate GetMyDelegateFromStringReflection(string methodName)
  {
      MyDelegate function = MyFunctionsClass.CallMethodOne;
  
      Type inf = typeof(MyFunctionsClass);
      foreach (var method in inf.GetMethods())
      {
          if (method.Name == methodName)
          {
              function = (MyDelegate)Delegate.CreateDelegate(typeof(MyDelegate), method);
          }
      }
  
      return function;
  }
  </code></pre>