Get method name in C #

Is there a way to get the name of the method that we currently find in it?

private void myMethod() { string methodName = __CurrentMethodName__; MessageBox(methodName); } 

Like this.ToString (), which returns the name of the class, is there any possible way to get the name of the method, for example, to track or track the application?

+4
source share
4 answers

It will give you a name -

 string methodName = System.Reflection.MethodInfo.GetCurrentMethod().Name; 

OR

 string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; 
+12
source

.NET 4.5 adds Caller Information attributes so you can use CallerMemberNameAttribute :

 using System.Runtime.CompilerServices; void myMethod() { ShowMethodName(); } void ShowMethodName([CallerMemberName]string methodName = "") { MessageBox(methodName); } 

This has the advantage of baking in the method name at compile time rather than run time. Unfortunately, there is no way to prevent someone from calling ShowMethodName("Not a real Method") , but this may not be necessary.

+6
source

Just

 public string MyMethod() { StackTrace st = new StackTrace (); StackFrame sf = st.GetFrame (1); string methodName = sf.GetMethod().Name; } 
+4
source

You can get information about a method like this

 var method = MethodInfo.GetCurrentMethod(); var name = method.Name; //get method name var parameters = method.GetParameters(); //get method parameters 
+2
source

Source: https://habr.com/ru/post/1495217/


All Articles