JulianR
JulianR

Reputation: 16513

Generics: why won't this compile?

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

Upvotes: 0

Views: 226

Answers (3)

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

A.Add() is expecting a T. You're giving it a C. This is okay as long as the compiler knows that a C is a T.

But that's not what your constraint says. It only says that a T is a C, which is the opposite.

Upvotes: 2

Yishai
Yishai

Reputation: 91881

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.

Upvotes: 4

Jimmy
Jimmy

Reputation: 91462

because T could be a subclass of C.

you can't add a Animal bob = new Fish() to a List<Giraffe>

Upvotes: 3

Related Questions