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
}
}
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
}
}
Console.WriteLine(new StackFrame().GetMethod().DeclaringType);
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.
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
Since static methods cannot be inherited the class name will be known to you when you write the method. Why not just hardcode it?