Languages
[Edit]
EN

C# / .NET - get current method name

15 points
Created by:
AnnLen
1765

In this article, we're going to have a look at how to get currently called method name in C# / .NET.

Quick solution:

string methodName = nameof(this.SomeMethodHere);   //  C# 6 or later

// or

MethodBase method = MethodBase.GetCurrentMethod(); //  call it inside your method
string methodName = method.Name;

There are two approaches how to do it:

  • with built-in nameof operator - introduced in C# 6,
  • with Reflection API.

1. nameof operator example

This approach is based on built-in keyword that does not use:

  • using statement that attach reflection namespaces, it is not necessary to attach:
    using System.Diagnostics; and using System.Reflection;
  • additional classes that reflects existing code. 

Note: the nameof operator is available in C# 6 and later.

using System;

public static class Program
{
	private static void DoMethod()
	{
		string name = nameof(DoMethod);

		Console.WriteLine("Currently called method name is " + name);
	}

	public static void Main(string[] args)
	{
		DoMethod();
	}
}

Output:

Currently called method name is DoMethod.

2. MethodBase.GetCurrentMethod method example

This solution was introduced in earlier version of .NET - can be used without warring it is not supported.

using System;
using System.Diagnostics;
using System.Reflection;

public static class Program
{
	private static void DoMethod()
	{
		MethodBase method = MethodBase.GetCurrentMethod();

		Console.WriteLine("Currently called method name is " + method.Name);
	}

	public static void Main(string[] args)
	{
		DoMethod();
	}
}

Output:

Currently called method name is DoMethod.

3. StackTrace class example

It is additional alternative way for previous examples.

using System;
using System.Diagnostics;
using System.Reflection;

public static class Program
{
	private static void DoMethod()
	{
		StackTrace trace = new StackTrace();

		StackFrame frame = trace.GetFrame(0);
		MethodBase method = frame.GetMethod();

		Console.WriteLine("Currently called method name is " + method.Name + ".");
	}

	public static void Main(string[] args)
	{
		DoMethod();
	}
}

Output:

Currently called method name is DoMethod.

References

  1. StackTrace Class - Microsoft docs
  2. StackFrame.GetMethod Method - Microsoft docs
  3. nameof operator - Microsoft Docs

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍