Thursday, December 30, 2010

C# Snippets - Get executing method name

Recently while working on a C# application we had a requirement like, every method should log its name when called. Here is the solution I came up with to output the method name. The Utils.DispMethodName() utilizes the StrackTrace .Net class to get the method name from which it was invoked from.


using System.Diagnostics;
public static class  Utils
{
  public static void DispMethodName()
 {
    string MethodName;
    string ClassName;
    MethodName = (new StackTrace(true)).GetFrame(1).GetMethod().Name;
    ClassName = (new StackTrace(true)).GetFrame(1).GetMethod().ReflectedType.Name;
    Console.WriteLine("Invoking " + ClassName + "." + MethodName);
 }
}

public class Alpha
{
 public void Foo1()
 {
   Utils.DispMethodName(); 
 }
}
Now, if you were to create an instance of class Alpha and invoke method Foo1(), this would print out "Alpha.Foo" to screen.

No comments: