Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of a method strongly typed

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.

like image 991
hikalkan Avatar asked Sep 14 '13 09:09

hikalkan


Video Answer


1 Answers

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

Output

like image 62
Will Faithfull Avatar answered Sep 17 '22 05:09

Will Faithfull