How can I get the name of the parent class of some class using Reflection?
9 Answers
Like so:
typeof(Typ).BaseType.Name
-
1
-
1@Alexandre I don't think that that's correct;
TypeOfdoesn't return a value, it's used as a comparator. EgIf TypeOf Typ Is Object Then .... The VB equivalent of C#'stypeof(Typ)isGetType(Typ). Or you can use Type.GetType("NameOfTyp")`. All overly confusing, I think. Sep 22, 2019 at 17:17
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. ;-)
-
1This 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
Type type = obj.GetType();
Type baseType = type.BaseType;
string baseName = baseType.Name;
The question above is asking about the Parent Type, which can be retrieved using:
yourRefVar.GetType().UnderlyingSystemType.Name
Currently in .NET Core, BaseType is not available, you can retrieve it by:
typeof(T).GetTypeInfo().BaseType
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;
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.