5

Closed as exact duplicate of "How can I find the method that called the current method?"

Is this possible with c#?

void main()
{
   Hello();
}

void Hello()
{
  // how do you find out the caller is function 'main'?
}
Community
  • 1
  • 1
Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138
  • http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method ? – Firas Assaad Nov 11 '08 at 09:30
  • This question is a duplicate of [http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method](http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method) – Drew Noakes Nov 11 '08 at 09:30

2 Answers2

18
Console.WriteLine(new StackFrame(1).GetMethod().Name);

However, this is not robust, especially as optimisations (such as JIT inlining) can monkey with the perceived stack frames.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • Hi, Marc. Would it be possible, because of JIT, that a method name could change during Runtime? – Joe Mar 14 '12 at 13:50
  • @Joe it is certainly possible to not get what you *expected*, which could be due to inlining, or due to compiler-generated methods for things like anonymous methods and iterator blocks. I wouldn't expect it to be suddenly renamed completely, unless you are using an obfuscator. – Marc Gravell Mar 14 '12 at 14:14
3

From here:

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1);
System.Diagnostics.StackFrame sf = st.GetFrame(0);
string msg = sf.GetMethod().DeclaringType.FullName + "." +
sf.GetMethod().Name;
MessageBox.Show( msg );

But there is also a remark that this could not work with multi-threading.

schnaader
  • 49,103
  • 10
  • 104
  • 136
  • 1
    Many thanks for mentioning the remark. I was wondering why I got a `NullReferenceException` when I tried to get the method name from inside a new thread. – Animesh Jun 25 '12 at 05:27