How to get the name of the Generic Func <T> method passed to the method
I am trying to get the method name of a function passed to an object using .Net closure as follows:
Method signature
public IEnumerable<T> GetData<T>(Func<IEnumerable<T>> WebServiceCallback) where T : class { // either gets me '<LoadData>b__3' var a = nrdsWebServiceCallback.Method.Name; var b = nrdsWebServiceCallback.GetInvocationList(); return WebServiceCallback(); } I call it this way:
SessionStateService.Labs = CacheManager.GetData(() => WCFService.GetLabs(SessionStateService.var1, SessionStateService.var2)); View "b__3" instead of WCFServce.GetLabs (..) etc.
You are looking at the name of the lambda expression (generated by the compiler) instead of the name of the method called inside the lambda.
You should use <Expression<Func<T>> instead of Func<T> . Expressions can be analyzed and analyzed.
Try
public IEnumerable<T> GetData<T>(Expression<Func<IEnumerable<T>>> callbackExpression) where T : class { var methodCall = callbackExpression.Body as MethodCallExpression; if(methodCall != null) { string methodName = methodCall.Method.Name; } return callbackExpression.Compile()(); } What is actually passed into your function is the anonymous lambda function ( () => WCFService.Etc ), so you see the actual method name - <LoadData>b__3 - this is the auto- <LoadData>b__3 name of the anonymous method.
What you really want is a method called inside the called method. To do this, you need to delve into the expression. Instead of Func<IEnumerable<T>> define your parameter as Expression<Func<IEnumerable<T>>> and call this code:
var body = nrdsWebServiceCallback.Body as MethodCallExpression; if (body != null) Console.WriteLine(body.Method.DeclaringType.Name + "." + body.Method.Name);