Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a class is derived from a generic class

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.

like image 232
bernhardrusch Avatar asked Jan 19 '09 14:01

bernhardrusch


People also ask

How do you know if a type is generic?

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.

Can a generic class be derived from another generic class?

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.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

What is difference between class and generic class?

The generic class works with multiple data types. A normal class works with only one kind of data type.


1 Answers

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; } 
like image 135
JaredPar Avatar answered Oct 06 '22 01:10

JaredPar