C# FAQ: How call a method using a name string


Jump to: navigation, search
CSharp-Online.NET:FAQs
edit

How call a method using a name string?

Reflection enables an application to locate the type containing the method, find the method within that type, and invoke the method—all starting with having only the method name in a string.

The following is a simple—reflection can do much more than this—example that finds a public method which passes no parameters and returns void:

using System;
using System.Reflection;
 
class CallMethodByName
{
   string name;
    
   CallMethodByName (string name)
   {
      this.name = name;
   }
    
   public void DisplayName()      // method to call by name
   {
      Console.WriteLine (name);   // prove we called it
   }
    
   static void Main()
   {
      // Instantiate this class
      CallMethodByName cmbn = new CallMethodByName ("CSO");
 
      // Get the desired method by name: DisplayName
      MethodInfo methodInfo = 
         typeof (CallMethodByName).GetMethod ("DisplayName");
 
      // Use the instance to call the method without arguments
      methodInfo.Invoke (cmbn, null);
   }
}

See also





Personal tools

AbeBooks.com – Textbooks