tags:

views:

276

answers:

5

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

+14  A: 
MethodInfo.GetCurrentMethod().Name
leppie
he's fast on the type. =)
StingyJack
thanks,exactly what I needed :D
DrG
I am bored at work :)
leppie
This works great, but remember to be careful with it in special methods like property gets and sets. The name will not look exactly like the method name in code for special methods. Easy enough to strip out the special part.
Mike Two
+3  A: 

System.Reflection.MethodBase.GetCurrentMethod().Name

StingyJack
+2  A: 

MethodBase.GetCurrentMethod()

Brian Genisio
+2  A: 

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;
mookid8000
+1  A: 

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;
DrG
But you asked about the method name. Not the others, they are not part of the method name.
StingyJack
and you should post this in an edit of your question, not as an answer.
StingyJack