user460667
user460667

Reputation: 1940

Determine whether object is a Generic

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
    }
}

Upvotes: 0

Views: 90

Answers (1)

Jon
Jon

Reputation: 437336

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.

Upvotes: 5

Related Questions