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.
Use Reflection from the Type of the current class.
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:
documentation
if you want to check if a class is subclass of another you can use is.
Docs: https://msdn.microsoft.com/en-us/library/scekt9xw.aspx
The Type.BaseType property is what you're looking for.
you can just use base.
This will get the base type (if it exists) and create an instance of it:
Alternatively, if you don't know the type at compile time use the following:
See
Type.BaseType
andActivator.CreateInstance
on MSDN.