Question

I have a class containing a generic Type:

class MyClass<T>
{
}

The T type can be any type, including MyClass<AnotherType>. Yes, that's kinda recursive, can have things like MyClass<MyClass<MyClass<T>>>.

At some point, inside MyClass, I want to know if T is MyClass<AnyOtherType> or any type derived from MyClass<AnyOtherType>. (Doesn't matter what AnyOtherType is, just need to know if T is MyClass).

So, how do I compare T type with MyClass<anything>?


Another thing I figured out, to avoid problems with the paramter, is to make MyClass<T> inherit MyClass (with no parameters), to make the comparison easier.

class MyClass<T> : MyClass

But still the question remains:

How can I compare T with MyClass to know if it's some type that inherits MyClass??
Was it helpful?

Solution

You would have to check with reflection - recursively to account for "derived from":

static bool IsMyClass(object obj)
{
    return obj == null ? false : IsMyClass(obj.GetType());
}
static bool IsMyClass(Type type)
{
    while (type != null)
    {
        if (type.IsGenericType &&
            type.GetGenericTypeDefinition() == typeof(MyClass<>))
        {
            return true;
        }
        type = type.BaseType;
    }
    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top