EN
C# / .NET - get current method name
15
points
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;
andusing 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.