TrN
TrN

Reputation: 1250

How to get real method name istead of .ctor?

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> ?

Upvotes: 3

Views: 1161

Answers (1)

dlchambers
dlchambers

Reputation: 3752

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 :)

Upvotes: 2

Related Questions