I want to be able to find all parent types (base classes and interfaces) for a specific type.
EG if i have
class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }
i want to see that A is B C D and E and Object
Whats the best way to do this? is there a reflection method to do this or do i need to make myself something.
====EDIT====
So something like this?
public static IEnumerable<Type> ParentTypes(this Type type)
{
foreach (Type i in type.GetInterfaces())
{
yield return i;
foreach (Type t in i.ParentTypes())
{
yield return t;
}
}
if (type.BaseType != null)
{
yield return type.BaseType;
foreach (Type b in type.BaseType.ParentTypes())
{
yield return b;
}
}
}
I was kinda hoping i didn't have to do it myself but oh well.
Interfaces are not classes, however, and an interface can extend more than one parent interface.
An interface defines how other classes can use your code. A base class helps implementers to implement your interface.
My rule of thumb: If you want to provide some common functionality accessible to a subset of classes, use a base class. If you want to define the expected behavior of of a subset of classes, use an interface.
An interface defines a contract. Any class or struct that implements that contract must provide an implementation of the members defined in the interface. Beginning with C# 8.0, an interface may define a default implementation for members.
More general solution:
public static bool InheritsFrom(this Type type, Type baseType)
{
// null does not have base type
if (type == null)
{
return false;
}
// only interface or object can have null base type
if (baseType == null)
{
return type.IsInterface || type == typeof(object);
}
// check implemented interfaces
if (baseType.IsInterface)
{
return type.GetInterfaces().Contains(baseType);
}
// check all base types
var currentType = type;
while (currentType != null)
{
if (currentType.BaseType == baseType)
{
return true;
}
currentType = currentType.BaseType;
}
return false;
}
Or to actually get all parent types:
public static IEnumerable<Type> GetParentTypes(this Type type)
{
// is there any base type?
if (type == null)
{
yield break;
}
// return all implemented or inherited interfaces
foreach (var i in type.GetInterfaces())
{
yield return i;
}
// return all inherited types
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
yield return currentBaseType;
currentBaseType= currentBaseType.BaseType;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With