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:
xxxxxxxxxx
1
string methodName = nameof(this.SomeMethodHere); // C# 6 or later
2
3
// or
4
5
MethodBase method = MethodBase.GetCurrentMethod(); // call it inside your method
6
string methodName = method.Name;
There are two approaches how to do it:
- with built-in nameof operator - introduced in C# 6,
- with Reflection API.
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.
xxxxxxxxxx
1
using System;
2
3
public static class Program
4
{
5
private static void DoMethod()
6
{
7
string name = nameof(DoMethod);
8
9
Console.WriteLine("Currently called method name is " + name);
10
}
11
12
public static void Main(string[] args)
13
{
14
DoMethod();
15
}
16
}
Output:
xxxxxxxxxx
1
Currently called method name is DoMethod.
This solution was introduced in earlier version of .NET - can be used without warring it is not supported.
xxxxxxxxxx
1
using System;
2
using System.Diagnostics;
3
using System.Reflection;
4
5
public static class Program
6
{
7
private static void DoMethod()
8
{
9
MethodBase method = MethodBase.GetCurrentMethod();
10
11
Console.WriteLine("Currently called method name is " + method.Name);
12
}
13
14
public static void Main(string[] args)
15
{
16
DoMethod();
17
}
18
}
Output:
xxxxxxxxxx
1
Currently called method name is DoMethod.
It is additional alternative way for previous examples.
xxxxxxxxxx
1
using System;
2
using System.Diagnostics;
3
using System.Reflection;
4
5
public static class Program
6
{
7
private static void DoMethod()
8
{
9
StackTrace trace = new StackTrace();
10
11
StackFrame frame = trace.GetFrame(0);
12
MethodBase method = frame.GetMethod();
13
14
Console.WriteLine("Currently called method name is " + method.Name + ".");
15
}
16
17
public static void Main(string[] args)
18
{
19
DoMethod();
20
}
21
}
Output:
xxxxxxxxxx
1
Currently called method name is DoMethod.