Ashish wrote:
it's okay if this throws runtime error on
mysecondcol[0] = new SomeOtherImplementationOfIBaseInterface();
but i should be able to hold a reference since Address is a narrower
type of IBaseEntity...
No, you shouldn't, because the whole point of generics is to catch
these things at compile time and therefore to avoid having to generate
code to trap invalid casts at runtime (which costs). If you were
allowed to do what you're proposing, then everywhere you used a generic
structure the compiler would also have to write in run-time type
checking, which would slow things down considerably.
You're looking at the from the point of view of a reader: "If I'm going
to read this collection, I don't care whether it's declared to be a
collection of type A, or a collection of some base type of A." All well
and good, but for the purposes of writing to the collection, it does
matter.
Don't forget: there's already a way to have a collection that you can
regulate using run-time type checking of its contents: use an
ArrayList. Remember that in the 1.1 world there were collections in
which you could place any type of object and you took care of type
checking yourself.
In the 2.0 world, generics added the capability to have collections
that were locked down to a particular type (or any type derived from
that particular type). There is no capability to "broaden the scope" of
what's allowed in the collection for certain purposes. A collection is
of a particular type and that's all there is to it. Any relaxation of
that rule comes with (undesirable) run-time costs.
The only reasonable exception I can see would be to allow you to cast a
*read-only* collection of class A to a *read-only* collection of any
ancestor of class A, but that's probably too specific to justify the
work it would take to shoehorn it into the language.