How can I get the name of the parent class of some class using Reflection?
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. ;-)
Like so:
typeof(Typ).BaseType.Name
obj.GetType().BaseType.Name
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;
Type type = obj.GetType();
Type baseType = type.BaseType;
string baseName = baseType.Name;
Currently in .NET Core, BaseType is not available, you can retrieve it by:
typeof(T).GetTypeInfo().BaseType