C# Open generic type comparison. Generic<> is "parent" of Generic<T>?

116 Views Asked by At

I have a class MyGeneric<T>, and some cached data created from type MyGeneric<string>, MyGeneric<int>, MyGeneric<double>... etc.

Somewhere I have to check certain data to see if it is MyGeneric, I code like this:

if (data is MyGeneric<>) { // can't compile
    // ... do something
}

or

if (data.GetType() == typeof(MyGeneric<>)
    || typeof(MyGeneric<>).isAssginableFrom(data.GetType())) { 
    // no exception but none of these comparison works
}

or this kind of stupid implemention works but i'd like to throw it away:

if (data.GetType().Name.StartsWith(typeof(MyGeneric<>).Name) { ... }

Is there a way to check relations between actual data type and open generic type (MyGeneric<>) ?

1

There are 1 best solutions below

0
Matías Fidemraizer On BEST ANSWER

What you call open generic type is known as generic type definition:

if(data.GetType().GetGenericTypeDefinition() == typeof(MyGeneric<>))
{

}