44

In C#, how does one obtain a reference to the base class of a given class?

For example, suppose you have a certain class, MyClass, and you want to obtain a reference to MyClass' superclass.

I have in mind something like this:

Type  superClass = MyClass.GetBase() ;
// then, do something with superClass

However, it appears there is no suitable GetBase method.

JaysonFix
  • 2,515
  • 9
  • 28
  • 28

7 Answers7

61

Use Reflection from the Type of the current class.

 Type superClass = myClass.GetType().BaseType;
JoshJordan
  • 12,676
  • 10
  • 53
  • 63
23
Type superClass = typeof(MyClass).BaseType;

Additionally, if you don't know the type of your current object, you can get the type using GetType and then get the BaseType of that type:

Type baseClass = myObject.GetType().BaseType;

documentation

Dru Steeby
  • 166
  • 2
  • 12
Timothy Carter
  • 15,459
  • 7
  • 44
  • 62
5

This will get the base type (if it exists) and create an instance of it:

Type baseType = typeof(MyClass).BaseType;
object o = null;
if(baseType != null) {
    o = Activator.CreateInstance(baseType);
}

Alternatively, if you don't know the type at compile time use the following:

object myObject;
Type baseType = myObject.GetType().BaseType;
object o = null;
if(baseType != null) {
    o = Activator.CreateInstance(baseType);
}

See Type.BaseType and Activator.CreateInstance on MSDN.

jason
  • 236,483
  • 35
  • 423
  • 525
3

if you want to check if a class is subclass of another you can use is.

if (variable is superclass){ //do stuff }

Docs: https://msdn.microsoft.com/en-us/library/scekt9xw.aspx

VeYroN
  • 760
  • 9
  • 19
2

The Type.BaseType property is what you're looking for.

Type  superClass = typeof(MyClass).BaseType;
heavyd
  • 17,303
  • 5
  • 56
  • 74
2

obj.base will get you a reference to the parent object from an instance of the derived object obj.

typeof(obj).BaseType will get you a reference to the parent object's type from an instance of the derived object obj.

meklarian
  • 6,595
  • 1
  • 23
  • 49
-2

you can just use base.

Sergio
  • 8,125
  • 10
  • 46
  • 77