0

I'm trying to get the derived class type from a static method defined in the base class.
The structure looks like:

class BaseClass
{
    public static Type GetType()
    {
        return MethodBase.GetCurrentMethod().GetType();
    }
}

class Foo : BaseClass
{
}

I need the code Foo.GetType() to return Foo but it returns BaseClass :(
I have to get type without using generics or initializing an instance.
How can I achieve this?

Yves
  • 3,752
  • 4
  • 29
  • 43

2 Answers2

1

Why not use typeof(Foo)? Without more context on what you're doing, it looks like that should work perfectly.

Tim S.
  • 55,448
  • 7
  • 96
  • 122
1

Since Foo doesn't redeclare GetType, Foo.GetType() is effectively the same method as BaseClass.GetType(). So when you write Foo.GetType(), the compiler emits a call to BaseClass.GetType(), since BaseClass is the type that actually implements the method.

Anyway, what you're doing doesn't make sense ; if you write Foo.GetType(), you already know that you want it to return Foo, so you can just use typeof(Foo).

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758