January 18, 2009

Using Reflection To Get Method Name

Output test class and method name:
string classAndMethodName =
  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString() +
  "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString());
Now in Visual C# compiler versions 6, to get the class name we can use:
  string className = nameof(someClass);
and to get the method name
...
public static string GetCurrentMethodName([System.Runtime.CompilerServices.CallerMemberName] string name = "")
{
    return name;
}
...
  string methodName = GetCurrentMethodName()

No comments: