I know there are a few answers on the site on this and i apologize if this is in any way duplicate, but all of the ones I found does not do what I am trying to do.
I am trying to specify method info so I can get the name in a type safe way by not using strings. So I am trying to extract it with an expression.
Say I want to get the name of a method in this interface:
public interface IMyInteface
{
void DoSomething(string param1, string param2);
}
Currently I can get the name using THIS method:
MemberInfo GetMethodInfo<T>(Expression<Action<T>> expression)
{
return ((MethodCallExpression)expression.Body).Method;
}
I can call the helper method as follows:
var methodInfo = GetMethodInfo<IMyInteface>(x => x.DoSomething(null, null));
Console.WriteLine(methodInfo.Name);
But I am looking for the version that I can get the method name without specifying the parameters (null, null)
like this:
var methodInfo = GetMethodInfo<IMyInteface>(x => x.DoSomething);
But all attempts fail to compile
Is there a way to do this?
Delegate
orAction<string, string>
in non-generic alternative. In this case you should be able to pass a method group – Erievar methodInfo = GetMethodInfo<IMyInteface>(DoSomething);
instead ofvar methodInfo = GetMethodInfo<IMyInteface>(x => x.DoSomething);
? Also, I still think specifying (default(string), default(string)) - is more readable, and you can support overloading methods in this case – PolygynyMethodInfo
from your approach is not very correct everytime, see this thread lambda-expression-not-returning-expected-memberinfo – Slatynameof
operator. Super easy and nets you compile-time checking in case of changes. Example:Console.WriteLine(nameof(DoSomething));
See: link – Finch