Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Method Name From Action

Tags:

c#

c#-4.0

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)); ) 
like image 363
Robert Avatar asked Mar 19 '11 19:03

Robert


People also ask

How to Get action method name in c#?

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.

What is action t used for in an application?

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.

What is an action 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.


1 Answers

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(){} } 
like image 100
jeroenh Avatar answered Oct 07 '22 09:10

jeroenh