Languages
[Edit]
EN

C# / .NET - get current method name

15 points
Created by:
Kelly
394

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
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join