Is it possible to get a method name from an action? I know I could always pass a string, but I was hoping for something a little more clever.
public bool DeviceCommand(Action apiCall) { //It would be nice to log the method name that was passed in try { apiCall(); } catch (Exception exc) { LogException(exc); return false; } return true; }
Usage looks like this:
void MyMethod() ( DeviceCommand(() => api.WriteConfig(config)); )
Action.Method.Name is returning the anonymous method name of the method that DeviceCommand() is contained in, not the actual api call. For example, Action.Method.Name returns MyMethod instead of WriteConfig. I updated my example usage to show this.
You can use the Action<T> delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.
Action delegate is an in-built generic type delegate. This delegate saves you from defining a custom delegate as shown in the below examples and make your program more readable and optimized. It is defined under System namespace.
Yes there is: Action.Method.Name
However, this only works if you pass in the Action parameter as a method group, not as a lambda expression:
class Program { static void SomeActionName(){} static void Main(string[] args) { LogMethodName(() => SomeActionName()); // <Main>b__0 LogMethodName(SomeActionName); // SomeActionName var instance = new SomeClass(); LogMethodName(() => instance.SomeClassMethod());; // <Main>b__1 LogMethodName(instance.SomeClassMethod); // SomeClassMethod } private static void LogMethodName(Action action) { Console.WriteLine(action.Method.Name); } } class SomeClass { public void SomeClassMethod(){} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With