Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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!

like image 660
Yegor Avatar asked Jan 17 '10 16:01

Yegor


People also ask

Can we use this in static method C#?

No, we can not used "this" keyword within a static method. because "this" keyword refers to the current instance of the class. Static Member functions do not have a this pointer (current instance).

Can we have non-static method in a static class in C#?

Static class always contains static members. Non-static class may contain both static and non-static methods. Static class does not contain an instance constructor.

What is static data type in C#?

A static variable is declared with the help of static keyword. When a variable is declared as static, then a single copy of the variable is created and shared among all objects at the class level. Static variables are accessed with the name of the class, they do not require any object for access. Example: C#


1 Answers

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

like image 88
JaredPar Avatar answered Sep 22 '22 21:09

JaredPar