Think that I have a class like below:
public class Foo
{
public int Bar { get; set; }
public int Sum(int a, int b)
{
return a + b;
}
public int Square(int a)
{
return a * a;
}
}
All you know that i can write a method that returns name of given property:
var name = GetPropertyName<Foo>(f => f.Bar); //returns "Bar"
GetPropertyName method can be implemented easily as below:
public static string GetPropertyName<T>(Expression<Func<T, object>> exp)
{
var body = exp.Body as MemberExpression;
if (body == null)
{
var ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
But I want to get a method name as easily as property name like below:
var name1 = GetMethodName<Foo>(f => f.Sum); //expected to return "Sum"
var name2 = GetMethodName<Foo>(f => f.Square); //expected to return "Square"
Is it possible to write such a GetMethodName method?
Note that: GetMethodName must be independent from signature or return value of the given method.
After some research, I've found that Expression<Action<T>>
should be sufficient to do what you want.
private string GetMethodName<T>(Expression<Action<T>> method)
{
return ((MethodCallExpression)method.Body).Method.Name;
}
public void TestMethod()
{
Foo foo = new Foo();
Console.WriteLine(GetMethodName<Foo>(x => foo.Square(1)));
Console.WriteLine(GetMethodName<Foo>(x => foo.Sum(1,1)));
Console.ReadLine();
}
public class Foo
{
public int Bar { get; set; }
public int Sum(int a, int b)
{
return a + b;
}
public int Square(int a)
{
return a * a;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With