Possible Duplicate:
.NET: Determine the type of “this” class in its static method
How can I make GetType()
accessible from a static
method?
I have this abstract base class
abstract class MyBase
{
public static void MyMethod()
{
var myActualType = GetType(); // this is an instance method
doSomethingWith(myActualType);
}
}
and an implementation of that class. (I could have many implementations.)
class MyImplementation : MyBase
{
// stuff
}
How can I get myActualType
to be typeof(MyImplementation)
?
The "type" within a static method is always the specific type, since there is no such thing as a virtual static method.
In your case, this means you can just write:
var myActualType = typeof(MyBase);
Since the "type" of MyMethod
, being a static, is always a static method of MyBase
.
What about this?
abstract class MyBase<T>
{
public static void MyMethod()
{
var myActualType = typeof(T);
doSomethingWith(myActualType);
}
}
class MyImplementation : MyBase<MyImplementation>
{
// stuff
}
This is the pattern i used.
abstract class MyBase
{
public static void MyMethod(Type type)
{
doSomethingWith(type);
}
}
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