54

How can I get the name of the parent class of some class using Reflection?

9 Answers 9

77

Like so:

typeof(Typ).BaseType.Name
2
  • 1
    In vb TypeOf(Typ).GetType().BaseType.Name
    – Alexandre
    Oct 24, 2013 at 11:08
  • 1
    @Alexandre I don't think that that's correct; TypeOf doesn't return a value, it's used as a comparator. Eg If TypeOf Typ Is Object Then .... The VB equivalent of C#'s typeof(Typ) is GetType(Typ). Or you can use Type.GetType("NameOfTyp")`. All overly confusing, I think.
    – SteveCinq
    Sep 22, 2019 at 17:17
39

I came to this question seeking the class which declares a nested class, which is the DeclaringType.

this.GetType().DeclaringType.Name

Maybe not what the OP asked, but maybe someone else comes here with the same search criteria as me. ;-)

1
  • 1
    This is also the right answer if you want the containing class for an enum. Again, not what the OP asked, but exactly what I wanted! Thanks Nov 13, 2018 at 16:24
19
obj.GetType().BaseType.Name
8

You can use:

string baseclassName = typeof(MyClass).BaseType.Name;
5
        Type type = obj.GetType();
        Type baseType = type.BaseType;
        string baseName = baseType.Name;
5

The question above is asking about the Parent Type, which can be retrieved using:

yourRefVar.GetType().UnderlyingSystemType.Name

2

Currently in .NET Core, BaseType is not available, you can retrieve it by:

typeof(T).GetTypeInfo().BaseType
2

I would like to add some more details, in case you need to find the ultimate parent class of your class, this code could help. I consider that I don't know whether the type is a class or an interface.

do
{
    if (type.IsInterface)
        if (type.BaseType == null)
            break;

    if (type.IsClass)
        if (type.BaseType == typeof(object))
            break;

    type = type.BaseType;

} while (true);

string ultimateBaseTypeName = type.Name;
0

Here's my solution for that (based on Oliamster's solution):

do
{
    if (type.DeclaringType is null)
        break;

    type = type.DeclaringType;
}
while (true);

string ultimateBaseTypeName = type.Name;

So for type A.B.C it will return A.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.