Wednesday, January 29, 2014

CSharp C# Stack output of method that called your method

CSharp C# Stack output of method that called your method

This is a simple example of using the StackFrame to determine the name of the method that called the current method.


Also consider:
Console.Writeline("Method:{0} was called by:{1}", new StackTrace().GetFrame(1).GetMethod().Name, new StackFrame(1, true).GetMethod().Name);

using System;
using System.Diagnostics;

namespace GetCallingMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            FirstCaller();
            Console.WriteLine();
            Console.ReadLine();
        }

        private static void FirstCaller()
        {
            CalledNow();
        }

        private static void CalledNow()
        {
            Console.WriteLine("Called by:{0}", new StackFrame(1, true).GetMethod().Name);
        }
    }
}



No comments:

Post a Comment