.NET: Determine the type of “this” class in its static method

Yegor picture Yegor · Jan 17, 2010 · Viewed 66.4k times · Source

In a non-static method I could use this.GetType() and it would return the Type. How can I get the same Type in a static method? Of course, I can't just write typeof(ThisTypeName) because ThisTypeName is known only in runtime. Thanks!

Answer

JaredPar picture JaredPar · Jan 17, 2010

If you're looking for a 1 liner that is equivalent to this.GetType() for static methods, try the following.

Type t = MethodBase.GetCurrentMethod().DeclaringType

Although this is likely much more expensive than just using typeof(TheTypeName).