How to get the methodname from a known method?

127 Views Asked by At

Is it possible to get the name of another method in the same class but without using a manually written string?

class MyClass {

    private void doThis()
    {
        // Wanted something like this
        print(otherMethod.name.ToString());
    }   

    private void otherMethod()
    {

    }
}

You may ask why: well the reason is that I must invoke the method later on like this Invoke("otherMethod"), however I don't want to hardcode this string myself as I can't refactor it anymore within the project.

4

There are 4 best solutions below

5
On BEST ANSWER

One approach is you can wrap it into delegate Action, then you can access the name of method:

string name = new Action(otherMethod).Method.Name;
3
On

Btw. I also found (in the expansions of the internet) an alternative solution for only getting the string of a method. It also works with parameters and return types:

System.Func<float, string> sysFunc = this.MyFunction;
string s = sysFunc.Method.Name; // prints "MyFunction"

public string MyFunction(float number)
{
    return "hello world";
}
0
On

You can use reflection (example - http://www.csharp-examples.net/get-method-names/) to get the method names. You can then look for the method that you're looking for by name, parameters or even use an attribute to tag it.

But the real question is - are you sure this is what you need? This looks as if you don't really need reflection, but need to think over your design. If you already know what method you're going to invoke, why do you need the name? How about a using a delegate? Or exposing the method via an interface and storing a reference to some class implementing it?

0
On

Try this:

MethodInfo method = this.GetType().GetMethod("otherMethod");
object result = method.Invoke(this, new object[] { });