user2043533
user2043533

Reputation: 751

Dynamically Invoke Method from method name string?

I have the following code:

 public string GetResponse()
    {
        string fileName = this.Page.Request.PathInfo;
        fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);

        switch (fileName)
        {
            case "GetEmployees":
                return GetEmployees();
            default:
                return "";
        }
    }

    public string GetEmployees()
    {

I will have many of these. They will all return a string and want to know if there is a way to avoid the switch case. If there is, is there a way to return "Not Found" if the method does not exist?

Thanks

Upvotes: 0

Views: 1365

Answers (1)

John Källén
John Källén

Reputation: 7983

Use reflection to obtain the methods:

public string GetResponse()
{
    string fileName = this.Page.Request.PathInfo;
    fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);

    MethodInfo method = this.GetType().GetMethod(fileName);
    if (method == null)
        throw new InvalidOperationException(
            string.Format("Unknown method {0}.", fileName));
    return (string) method.Invoke(this, new object[0]);
}

This assumes that the methods you are calling will always have 0 arguments. If they have varying number of arguments you will have to adjust the array of parameters passed to MethodInfo.Invoke() accordingly.

GetMethod has several overloads. The one in this sample will return public methods only. If you want to retrieve private methods, you need to call one of the overloads to GetMethod that accepts a BindingFlags parameter and pass BindingFlags.Private.

Upvotes: 1

Related Questions