3

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"

2 Answers 2

9

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;
    }
}
3
  • How about getting a method name from a specified type? i.e. Expression<Func<TSource, Action<TTarget>>>? Jan 26, 2012 at 6:26
  • @Shimmy: It's not really clear what you mean, to be honest. Might be worth a new question?
    – Jon Skeet
    Jan 26, 2012 at 6:28
  • I want this function: static MethodInfo GetMethod(Expression<Func<TTarget, EventHandler<TEventArgs>>> method), here is what I've tried so far, but it returns Delegate.CreateDelegate method. Jan 26, 2012 at 6:36
1

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".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.