0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

What happens when the method does not exist?
You get a null reference back from GetMethod. your code would have to validate this, and handle the missing method accordingly. I'll change the answer to reflect (pardon the pun) this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.