0

I have written the following code where I am trying to determine whether a generic classes type inherits from a base class. I think this is easier to explain what I am doing in code. Could anybody please provide some insight into how to get around this issue.

public class MyGeneric<T>
{
}

public class MyBaseClass
{
}

public class MyClass1 : MyBaseClass
{
}

static void Main(string[] args)
{
    MyGeneric<MyClass1> myList = new MyGeneric<MyClass1>();

    if(myList.GetType() == typeof(MyGeneric<>))
    {
        // Not equal
    }

    // This is the test I would like to pass!
    if(myList.GetType() == typeof(MyGeneric<MyBaseClass>))
    {
        // Not equal
    }

    if(myList.GetType() == typeof(MyGeneric<MyClass1>))
    {
        // Equal
    }
}
user460667
  • 1,870
  • 3
  • 19
  • 26
  • Does this question provide the answer? http://stackoverflow.com/questions/457676/c-reflection-check-if-a-class-is-derived-from-a-generic-class – Mike Chamberlain Jul 26 '11 at 12:23
  • This question might be a duplicate, but definitely **not** a duplicate of #457676. – Jon Jul 26 '11 at 12:29

1 Answers1

5

You need to use Type.GetGenericArguments to get an array of the generic arguments, and then check if they are part of the same hierarchy.

MyGeneric<MyClass1> myList = new MyGeneric<MyClass1>();

if(myList.GetType() == typeof(MyGeneric<>))
{
    // Not equal
}

// WARNING: DO NOT USE THIS CODE AS-IS!
//   - There are no error checks at all
//   - It should be checking that myList.GetType() is a constructed generic type
//   - It should be checking that the generic type definitions are the same
//     (does not because in this specific example they will be)
//   - The IsAssignableFrom check might not fit your requirements 100%
var args = myList.GetType().GetGenericArguments();
if (typeof(MyBaseClass).IsAssignableFrom(args.Single()))
{
    // This test should succeed
}

See also How to: Examine and Instantiate Generic Types with Reflection at MSDN.

Jon
  • 428,835
  • 81
  • 738
  • 806
  • Thanks. I did get it working in a manner similar to that, I was hoping there might have been a slightly cleaner single line manner. – user460667 Jul 26 '11 at 12:31