C#: Getting StackTrace and StackFrame to obtain debugging and diagnostic information for a method

The following method returns the current stack frame that holds info about the caller method (notice the “1” instead of “0”)

[MethodImpl( MethodImplOptions.NoInlining )]
public static StackFrame GetCurrentStackFrame() {
    StackTrace st = new StackTrace(true); //True to capture source information
    return st.GetFrame( 1 );

Having this, you can get info about method, file line number etc:

private void CallerMethod(){
    string s = GetCurrentStackFrame().GetMethod().Name;         //Get caller method name
    Type t1 = GetCurrentStackFrame().GetMethod().DeclaringType; //Get caller method class type
    Type t2 = GetCurrentStackFrame().GetMethod().ReflectedType; //Get caller method name class type
    string s2 = GetCurrentStackFrame().GetFileName();           //Get caller method file name
    int i =  GetCurrentStackFrame().GetFileLineNumber();        //Get caller method file number

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s