views:

110

answers:

2

Hi!

I know it is possible to retrieve a property name or a method with a return type. But is it also possible to get a method name without a return type via LINQ expression trees?

Example: string methodname = GetMethodname(x=>x.GetUser());

---> results: "GetUser"

+3  A: 

Absolutely - but you'll want a method signature like this:

public static string GetMethodName<T>(Expression<Action<T>> action)

(That means you'll need to specify the type argument when you call it, in order to use a lambda expression.)

Sample code:

using System;
using System.Linq.Expressions;

class Test
{
    void Foo()
    {
    }

    static void Main()
    {
        string method = GetMethodName<Test>(x => x.Foo());
        Console.WriteLine(method);
    }

    static string GetMethodName<T>(Expression<Action<T>> action)
    {
        MethodCallExpression methodCall = action.Body as MethodCallExpression;
        if (methodCall == null)
        {
            throw new ArgumentException("Only method calls are supported");
        }
        return methodCall.Method.Name;
    }
}
Jon Skeet
+1  A: 

You'll need something like this method:

public static string GetMethodName<T>(Expression<Action<T>> expression) {
    if (expression.NodeType != ExpressionType.Lambda || expression.Body.NodeType != ExpressionType.Call)
     return null;
    MethodCallExpression methodCallExp = (MethodCallExpression) expression.Body;
    return methodCallExp.Method.Name;
}

Call like this: GetMethodName<string>(s => s.ToLower()) will return "ToLower".

Julien Lebosquain