gettin the name of the method that I m currently running

  • Thread starter Thread starter Onur \Xtro\ ER
  • Start date Start date
O

Onur \Xtro\ ER

I need the name of current running method name for exception reporting. does
..NET have such a thing ?


example : (in delphi language)

Procedure TMyClass.MyMethod;
Begin
WriteLn(....some code here...) // writes 'MyMethod' to the
console with the help of '...some code...'
End;


is it possible to get the name of current running method ?
 
hi,
try, stacktrace property of exception object to get the whole trace
of the error and u'll come to know on which line of code the error
occured and thus u'll get the name of the method.
 
thank you but I dont want to parse the stack string if I have an other
chance.

is there a legal way of getting the current call stack list name by name in
an array or something ?
 
System.Diagnostics offers many classes that help on that point. StackTrace
and StackFrame are very interesting.

using System.Diagnostics;
MessageBox.Show(new StackFrame().GetMethod().Name);

example : (in delphi language)

Procedure TMyClass.MyMethod;
Begin
WriteLn(....some code here...) // writes 'MyMethod' to the
console with the help of '...some code...'
End;

can be replaced in C# by

class TMyClass {
void MyMethod() {
Console.WriteLine(new StackFrame().GetMethod().Name) // writes
'MyMethod' to the console
}
}

Hope it helps,

Ludovic SOEUR.
 
Try MethodBase.GetCurrentMethod() which returns a MethodBase
(constructor or method). Use MethodBase.Name to get the name. Use
MethodBase.DeclaringType to get the Type where the method is declared.
Use that Type.FullName if you want to print the fully qualified name of
the type for your reporting purpose.

Hope it helps,
Thi
 
Ludovic's is also good. StackFrame does provide some extra info
together with a MethodBase. If you don't want such info, use
MethodBase.GetCurrentMethod().Name instead. It is in the
System.Reflection namespace and I used it in many of my apps for
logging purpose. In case you want to get the name of the caller method
(or any method higher in the call stack, use StackTrace class.
 
Back
Top