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!
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).
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.
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#
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With