I have a generic class in my project with derived classes.
public class GenericClass<T> : GenericInterface<T> { } public class Test : GenericClass<SomeType> { }
Is there any way to find out if a Type
object is derived from GenericClass
?
t.IsSubclassOf(typeof(GenericClass<>))
does not work.
To examine a generic type and its type parametersGet an instance of Type that represents the generic type. In the following code, the type is obtained using the C# typeof operator ( GetType in Visual Basic, typeid in Visual C++). See the Type class topic for other ways to get a Type object.
In the same way, you can derive a generic class from another generic class that derived from a generic interface. You may be tempted to derive just any type of class from it. One of the features of generics is that you can create a class that must implement the functionality of a certain abstract class of your choice.
An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.
The generic class works with multiple data types. A normal class works with only one kind of data type.
Try this code
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck) { while (toCheck != null && toCheck != typeof(object)) { var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck; if (generic == cur) { return true; } toCheck = toCheck.BaseType; } return false; }
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