Malvin
Malvin

Reputation: 859

How to get the methodname from a known method?

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.

Upvotes: 6

Views: 122

Answers (4)

Malvin
Malvin

Reputation: 859

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";
}

Upvotes: 0

Romano Zumb&#233;
Romano Zumb&#233;

Reputation: 8079

Try this:

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

Upvotes: 1

Vadim
Vadim

Reputation: 2865

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?

Upvotes: 2

cuongle
cuongle

Reputation: 75306

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;

Upvotes: 8

Related Questions