Thursday 27 September 2012

Test for Generic Type

Useful helper method I found on StackOverflow

using System;
using System.Collections.Generic;

namespace TestForGenericType
{
class Program
{
static void Main(string[] args)
{
var test = new List<string>();
bool result = test.GetType().IsSubclassOfRawGeneric(typeof(List<>));

// result = true
}
}

static class ReflectionUtils
{
public static bool IsSubclassOfRawGeneric(this Type toCheck, Type baseType)
{
while (toCheck != typeof(object))
{
Type cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (baseType == cur)
{
return true;
}

toCheck = toCheck.BaseType;
}
return false;
}
}
}

No comments:

Post a Comment