Jorge Galvão
Jorge Galvão

Reputation: 1913

Is there a way to check if a Generic type is a subtype of another type in C#?

Given a generic type T I would want to check if it is a subtype of another type Other. I would expect that T is Other would work, but the only way I got it to work was with typeof(T).IsAssignableTo(typeof(Other)).

Is there a better way to do this?

Bellow there is an example usage:

public class Animal { }

public class AnimalFactory
{
    class FakeAnimal : Animal { }

    static FakeAnimal fakeCached = new FakeAnimal();

    public static Animal CreateAnimal<T>() where T : Animal, new()
    {
        //if (T is FakeAnimal) // -> Doesn't compile
        if (typeof(T).IsAssignableTo(typeof(FakeAnimal))) // -> Works fine
        {
            return fakeCached ;
        }
        return new T();
    }
}

Note: The example above is simplified, the concrete use case is more complex. I'm not concerned with anything else in the example other than the line that doesn't compile.

Upvotes: 1

Views: 250

Answers (1)

Moho
Moho

Reputation: 16563

The pattern matching statement x is FakeAnimal requires x be an object. T is a type name, which is why you must get the Type object via typeof(T) and use that object's IsAssignableTo method.

Upvotes: 2

Related Questions