Wednesday, 19 April 2017

C# code to get current method name

 /*
         C# code to get current method name
         This is how you could get the current method name in C#  code.
         You can use the snippet for dynamic logging purpose in your application.
          */
        static void GetFunctionName()
        {
            //Current function name
            string name = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Console.WriteLine("Current Function name:" + name);

            //Get Calling stackTrace
            StackTrace stackTrace = new StackTrace();
            name = stackTrace.GetFrames().Last().GetMethod().Name;
            Console.WriteLine("1st Calling Function name:" + name);

            foreach (var fn in stackTrace.GetFrames())
            {
                Console.Write(fn.GetMethod().Name + " > ");
            }
        }