Best way to illustrate my question is with this example code:
class Item {}
class Container< T > {}
class Program
{
static void DoSomething( ob
Try:
typeof(Container<>) == something.GetType().GetGenericTypeDefinition()
Note that this will only return true if the actual type is Container<T>
. It doesn't work for derived types. For instance, it'll return false
for the following:
class StringContainer : Container<string>
If you need to make it work for this case, you should traverse the inheritance hierarchy and test each base class for being Container<T>
:
static bool IsGenericTypeOf(Type genericType, Type someType)
{
if (someType.IsGenericType
&& genericType == someType.GetGenericTypeDefinition()) return true;
return someType.BaseType != null
&& IsGenericTypeOf(genericType, someType.BaseType);
}