Given the following code:
class A<T>
{
internal void Add(T obj) { }
}
class C { }
class B<T> where T : C
{
public B()
{
A<T> a = new A<T>();
a.Add(new C());
}
}
The call to Add does not compile. It does when I cast it to T first:
a.Add((T)new C());
It might be the sleep deprivation, but what am I missing here?
If T is of type C (note the constraint on B), then why isn’t A<T> equivalent to A<C>?
Because if B were declared with a type of D, which would be a class which extends C, then adding a new C would violate the type.