Method name from linq expression

How can I get the name of the first method called from an expression in C #? Something like the fictional MethodUtils.NameFromExpression () below:

Expression<Action<string>> expr = s => s.Trim(); Assert.AreEqual("Trim", MethodUtils.NameFromExpression(expr)); 

Ideally, any util method would be written / overloaded so that it can accept expressions for any of the Action or Func delegation types.

Thanks in advance.

UPDATE

I found the answer (see below), but would still like to know if this is a good solution or if there is a way to do this in BCL.

+6
c # lambda linq
source share
1 answer

Digging a bit with the debugger, and I answered my question:

 public static class MethodUtils { public static string NameFromExpression(LambdaExpression expression) { MethodCallExpression callExpression = expression.Body as MethodCallExpression; if(callExpression == null) { throw new Exception("expression must be a MethodCallExpression"); } return callExpression.Method.Name; } } 

Any comments on this implementation?

+10
source share

All Articles