tags:

views:

1237

answers:

6

Is it possible to print the class name from within a static function?

e.g ...

public class foo
{

    static void printName()
    {
        // Print the class name e.g. foo
    }

}
+2  A: 

StackTrace class can do that.

Anton Gogolev
+7  A: 
Console.WriteLine(new StackFrame().GetMethod().DeclaringType);
Matt Hamilton
+6  A: 

While the StackTrace answers are correct, they do have an overhead. If you simply want safety against changing the name, consider typeof(foo).Name. Since static methods can't be virtual, this should usually be fine.

Marc Gravell
That's a good point. Obviously if you control the method then you control the class name, so the whole thing's a bit academic.
Matt Hamilton
All I am using this for is to Log exceptional behaviour, so I can live with the overhead of using the Stack Trace Method as execution will (probably) cease after this logging activity.
TK
+2  A: 

A (cleaner, IMO) alternative (still slow as hell and I would cringe if I saw this in a production code base):

Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType);

By the way, if you're doing this for logging, some logging frameworks (such as log4net) have the ability built in. And yes, they warn you in the docs that it's a potential performance nightmare.

HTH, Kent

Kent Boogaart
A: 

Since static methods cannot be inherited the class name will be known to you when you write the method. Why not just hardcode it?

Vilx-
A: 

You may want to get the class name of a class template.