Site icon Tech Dreams

C# How To: Get Calling Class Name & Method Name Using StackFrame Class

In one of the .NET applications I’m designing, we had to identify the name of the calling method as well as the class in which the calling method is defined. This information helped us in automating our process and reduced the lines of code by several times.

It’s quite easy to get calling method details with the help of StackFrame.GetFrame method (available since .NET framework v 1.1). Here is the piece of code you would require

StackFrame class is part of System.Diagnostics namespace and this class helps us in identifying the stack trace information in a method call sequence. The parameter value 1 in the first line signifies the immediate calling method information. You can increase the parameter value by required number to dig deeper into the method calling stack.

Note: C# compilers some times optimizes the code and replaces method calls with inline code. So when such optimization is performed by C# compiler, the above described method fails to get the name of the calling method.  In our requirement we were very sure that C# compiler is not going to do any such optimization and we used this code.

Exit mobile version