Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetType in static method [duplicate]

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

like image 483
Daniel A. White Avatar asked Oct 20 '11 17:10

Daniel A. White


3 Answers

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.

like image 83
Reed Copsey Avatar answered Nov 03 '22 23:11

Reed Copsey


What about this?

abstract class MyBase<T>
{
   public static void MyMethod()
   {
      var myActualType = typeof(T);
      doSomethingWith(myActualType);
   }
}


class MyImplementation : MyBase<MyImplementation>
{
    // stuff
}
like image 22
matt Avatar answered Nov 03 '22 23:11

matt


This is the pattern i used.

abstract class MyBase
{
   public static void MyMethod(Type type)
   {
      doSomethingWith(type);
   }
}
like image 3
Daniel A. White Avatar answered Nov 03 '22 22:11

Daniel A. White