Odys
Odys

Reputation: 9080

Can I get the name of a method by providing the method itself?

Is there a way to get a method's name (as a string) by providing the method itself?

class Person
{
    bool Eat(Food food){...}
}

I want to somehow get the string "Eat". That's all! This can either be from an instance or from the class declaration using reflection.

My attempt:

public delegate bool EatDelegate(Food f);

EatDelegate eatDel = new EatDelegate(_person1.Eat);
string methodName = eatDel.GetInvocationList()[0].Method.Name;

This requires to know the method's delegate and the whole thing is unreadable

I want the methodName in order to dynamically invoke it.

Notes:

Upvotes: 4

Views: 119

Answers (2)

L.B
L.B

Reputation: 116108

public string GetName(Expression<Action> exp)
{
    var mce = exp.Body as MethodCallExpression;
    return mce.Method.Name;
}

--

a Method

public int  MyMethod(int i)
{
    return 0;
}

and usage

 var s= GetName(()=>this.MyMethod(0));

Upvotes: 5

Furqan Safdar
Furqan Safdar

Reputation: 16698

var methods = typeof(Person).GetMethods();
foreach (var method in methods)
{
    if (method.Name.Equals("Eat"))
    {
         // do something here...
    }
}

Upvotes: 0

Related Questions