Showing posts with label Currently Executing Method. Show all posts
Showing posts with label Currently Executing Method. Show all posts

Wednesday, January 7, 2009

Retrieve the name of the currently executing method inside the same method.



In one of my projects, the requirement was to log the error information inside a method if an exception occurs. I needed to record the current method name along with the error message. The code was like this:
public void DoSomething()
{
try
{
//The method code goes here.
}
catch (Exception ex)
{
WriteLog("DoSomething", ex.ToString());
//The first parameter of WriteLog method is the name of the current method.
}
}

I was not happy with the way I had to hard code the name of the current method(“DoSomething” here). This way I had to hard code the names of every method where I needed to log the error information.This required to change every method name in the lines of log writing if i had to change the method name.So I was looking for a built in feature that will provide me the current method name.I searched for a while and found a handy solution in the “System.Diagnostics” namespace of the .NET Framework.Here is the code to automatically get the name of the current method.

public void DoSomething()
{
try
{
//The method code goes here.
}
catch (Exception ex)
{
string currentMethodName = new
System.Diagnostics.StackTrace().GetFrame(0).GetMethod().Name;

//The "GetMethod" method returns a "MethodBase" object.With
//this we can access the name of the method and
//other valuable information like access
//modifier,parameters,return types e.tc.//

WriteLog(currentMethodName, ex.ToString());
}
}
I found the API provided by the “System.Diagnostics” namespace really interesting and useful.