C# : how do you obtain a class' base class?

Use Reflection from the Type of the current class.

 Type superClass = myClass.GetType().BaseType;

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


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.

Tags:

C#

Superclass