Normally I can call this.GetType(), but I can't access this in a static method. How can we check it?
Asked
Active
Viewed 2.7k times
23
-
4Look: http://stackoverflow.com/questions/552629/c-sharp-print-the-class-name-from-within-a-static-function – k06a Feb 17 '12 at 10:09
2 Answers
38
new StackFrame().GetMethod().DeclaringType
or
MethodBase.GetCurrentMethod().DeclaringType
or
new StackTrace(true).GetFrame(<frame index>).GetMethod() //e.g. <frame index> = 0

alexsuslin
- 4,130
- 1
- 20
- 30
13
Use typeof:
string className = typeof(MyClass).Name;

brgerner
- 4,287
- 4
- 23
- 38
-
4
-
-
1@lo If you copy class by ReSharper's *Copy Type* refactoring the typeof statement should remain correct too. – brgerner Feb 17 '12 at 12:15
-
1By this same token, you can now simply do `nameof(MyClass)`, as of C# 6.0. – Kevin May 13 '19 at 18:58