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.