As I understand this, the question isn't how to call a method via a delegate, but how to get the name of a method without resorting to magic strings.
Using reflection doesn't make the magic strings go away. You can get all methods of a type with a specific signature, but you still need to know the name of the method you are targeting. A simple rename refactoring will still break your code.
A typical solution in such cases is to pass an Expression pointing to the member you want. This is used extensively in MVVM frameworks to pass the name of any modified parameters
The following method will check if the supplied expression is an actual method call and extract the method's name:
public static bool TryGetName(Expression<Action> expr, out string memberName)
{
memberName = null;
var body = expr.Body as MethodCallExpression;
if (body == null)
return false;
memberName = body.Method.Name;
return true;
}
The method can be called like this:
bool success=TryGetName(()=>someObject.SomeMethod(), out name);
All Action and Func objects inherit from Action, which means that SomeMethod
may actually be a function. If the method contains parameters, the call will need some dummy values:
bool success=TryGetName(()=>someObject.SomeMethod(null,"dummy",0), out name);