Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# print the class name from within a static function

Tags:

c#

static

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     }  } 
like image 270
TK. Avatar asked Feb 16 '09 08:02

TK.


1 Answers

You have three options to get the type (and therefore the name) of YourClass that work in a static function:

  1. typeof(YourClass) - fast (0.043 microseconds)

  2. MethodBase.GetCurrentMethod().DeclaringType - slow (2.3 microseconds)

  3. new StackFrame().GetMethod().DeclaringType - slowest (17.2 microseconds)


If using typeof(YourClass) is not desirable, then MethodBase.GetCurrentMethod().DeclaringType is definitely the best option.

like image 150
Jamezor Avatar answered Oct 26 '22 20:10

Jamezor