0

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<>) ?

ineztia
  • 815
  • 1
  • 13
  • 29

1 Answers1

3

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

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

}
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206