HomeCSharpC# Tips & Tricks #22 – Get Name of the Current Executing Method

C# Tips & Tricks #22 – Get Name of the Current Executing Method

If you are looking at a way to get the name of the current method in C#, here’s a quick tip in C# on how to do it with few options.

How to Get Name of the Current Method Using in C# ?

Option 1 : Using Reflection

One of the easiest way to do it is using reflection. The Reflection name space provides the MethodBase class which exposes the GetCurrentMethod to get the method information.

System.Reflection.MethodBase.GetCurrentMethod().Name;

Here’s a sample code snippet in C# demonstrating how to get the current method name using reflection.

using System;
namespace AbundantCode
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
            Console.WriteLine(MethodName);
            Console.ReadLine();
        }
    }
}

Note : This would work for non-sync methods.

Option 2 : Using the StackTrace Class.

The Other option to get the name of the method is using the StackTrace method and getting the stack frame to fetch the method information as shown in the below code snippet.

using System;
using System.Diagnostics;
namespace AbundantCode
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sTrace = new StackTrace();
            var Frame = sTrace.GetFrame(0);
            var currentMethodName = Frame.GetMethod().Name;
            Console.WriteLine(currentMethodName);

            Console.ReadLine();
        }
    }
}

Output

Leave a Reply

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...