Search code examples
c#.nettypesstatic-methods

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


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!


Solution

  • 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).