Ian G
Ian G

Reputation: 30234

Can I find out the name of the method I am using?

Say I have some code like

namespace Portal
{
  public class Author
    {
        public Author() { }
        private void SomeMethod(){
          string myMethodName = ""; 
          //  myMethodName = "Portal.Author.SomeMethod()";
        }
    }
}

Can I find out the name of the method I am using? In my example I'ld like to programmatically set myMethodName to the name of the current method (ie in this case "Portal.Author.SomeMethod").

Thanks

Upvotes: 3

Views: 429

Answers (5)

Ian G
Ian G

Reputation: 30234

While @leppie put me on the right track, it only gave me the name of the method, but if you look at my question you will see I wanted to include namespace and class information...

so

myMethodName = System.Reflection.MethodBase.GetCurrentMethod().ReflectedType + 
                 "." + System.Reflection.MethodBase.GetCurrentMethod().Name;

Upvotes: 1

mookid8000
mookid8000

Reputation: 18628

System.Diagnostics has the StackFrame/StackTrace which allows you to just that, including more. You can inspect the entire call stack like so:

StackFrame stackFrame = new StackFrame(1, true); //< skip first frame and capture src info
StackTrace stackTrace = new StackTrace(stackFrame);
MethodBase method = stackTrace.GetMethod();
string name = method.Name;

Upvotes: 2

Brian Genisio
Brian Genisio

Reputation: 48127

MethodBase.GetCurrentMethod()

Upvotes: 2

StingyJack
StingyJack

Reputation: 19459

System.Reflection.MethodBase.GetCurrentMethod().Name

Upvotes: 3

leppie
leppie

Reputation: 117220

MethodInfo.GetCurrentMethod().Name

Upvotes: 14

Related Questions