Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the name of the currently executing method in dotnet core

Tags:

I want to get the name of the currently executing method in a dotnet core application.

There are lots of examples of how to do this with regular c# eg

  • Get the name of the current method
  • How to get the name of the current method from code

However the apis for both methods appear not to be there in core yet (see https://github.com/dotnet/corefx/issues/1420)

Is there another way I can get the executing method name in .net core?

like image 861
Not loved Avatar asked Dec 13 '16 01:12

Not loved


People also ask

How to Get name of Current method?

Using MethodBase.GetCurrentMethod() method can be used, which returns a MethodBase object representing the currently executing method. That's all about getting the name of the current method in C#.


2 Answers

CallerMemberNameAttribute Allows you to obtain the method or property name of the caller to the method.

public void DoProcessing() {     TraceMessage("Something happened."); }  public void TraceMessage(string message,         [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",         [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",         [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0) {     System.Diagnostics.Trace.WriteLine("message: " + message);     System.Diagnostics.Trace.WriteLine("member name: " + memberName);     System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);     System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber); }  // Sample Output: //  message: Something happened. //  member name: DoProcessing //  source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs //  source line number: 31 
like image 119
feiyun0112 Avatar answered Oct 21 '22 15:10

feiyun0112


Simplest way is to use :

System.Reflection.MethodBase.GetCurrentMethod().Name

like image 41
Akarsha Avatar answered Oct 21 '22 15:10

Akarsha