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:

 

There are two approaches how to do it:

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

1. nameof operator example

Edit

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.

Output:

2. MethodBase.GetCurrentMethod method example

Edit

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

Output:

3. StackTrace class example

Edit

It is additional alternative way for previous examples.

Output:

References

Edit
  1. StackTrace Class - Microsoft docs
  2. StackFrame.GetMethod Method - Microsoft docs
  3. nameof operator - Microsoft Docs
1
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