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));
)
If your invocations of DeviceCommand are always going to be of the form
then you could modify DeviceCommand to take an expression tree as a parameter. This would allow you to drill down into the tree to get the information you want (in this case, the string “SomeMethod”), then compile the tree into a delegate and execute it:
Of course, building and compiling an expression tree every time could be a major performance issue (or not–it just depends on how often
DeviceCommandis called). You’ll have to decide if the performance implications (and general “hack”ishness of this approach) are worth it in your situation.