Rookian
Rookian

Reputation: 20539

LINQ Is it possible to get a method name without a return type via LINQ expression trees?

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"

Upvotes: 3

Views: 1008

Answers (2)

Julien Lebosquain
Julien Lebosquain

Reputation: 41213

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499860

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

Upvotes: 9

Related Questions