How to get real method name istead of .ctor?

1.1k Views Asked by At

Hi i have method getting the name of calling method:

    public static string GetMethodName()
    {
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(); 
        return trace.GetFrame(1).GetMethod().Name;
    }

And when I track my bugs and exceptions I always get method name .ctor how to avoid that or at least get something like ClassName<.ctor> ?

1

There are 1 best solutions below

1
On BEST ANSWER

How about:

StackTrace stackTrace = new StackTrace();
foreach(StackFrame sf in stackTrace.GetFrames())
{
   if (!sf.GetMethod().Name.StartsWith("."))    // skip all the ".ctor" methods
   {
       return sf.GetMethod().DeclaringType.Name + "." + sf.GetMethod().Name;
   }
}
return "??"; // What do you want here?

Using a string compare is a bit heavy-handed, but it works :)