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

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...