Skip to content

Instantly share code, notes, and snippets.

@dfmartin
Created June 4, 2013 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfmartin/5703425 to your computer and use it in GitHub Desktop.
Save dfmartin/5703425 to your computer and use it in GitHub Desktop.
Comparing Type with GenericType to determine if a type is derived from a generic type where the generic argument type is unknown.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.IsTrue(typeof(Foo<>).IsAssignableFrom(typeof(Bar))); // fails
}
[TestMethod]
public void TestIsSubClassOfRaw()
{
Assert.IsTrue(IsSubclassOfRawGeneric(typeof(Foo<>), typeof(Bar))); // passes
}
[TestMethod]
public void GetGenericTypeDef()
{
Assert.AreEqual(typeof(Foo<>), typeof(Bar).BaseType.GetGenericTypeDefinition()); // passes
}
[TestMethod]
public void IsSubClassBasic()
{
Assert.IsTrue(typeof(Bar).IsSubclassOf(typeof(Foo<>))); // fails
}
static bool IsSubclassOfRawGeneric(Type generic, Type toCheck)
{
//method borrowed from StackOverflow question http://stackoverflow.com/a/457708/117428
while (toCheck != null && toCheck != typeof(object))
{
var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
if (generic == cur)
{
return true;
}
toCheck = toCheck.BaseType;
}
return false;
}
}
internal class Bar : Foo<string>
{
}
internal class Foo<T>
{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment