On Apr 5, 2008, at 23:25, Aristotle Pagaltzis wrote:
* Marco Von Ballmoos <[email protected]> [2008-04-05 00:10]:
C#'s generics are better, but still forbid covariance
Have to, to ensure type safety.
"Have to" is a bit strong. "Willing to accept the restriction on
expressiveness in exchange for an absolutely foolproof type system"
is more accurate. The classic problem with covariance is that it
becomes possible to generate -- quite unwittingly -- a configuration
of objects that is statically valid, but dynamically invalid. I wrote
an article a while back about an interesting paper on the subject:
http://earthli.com/news/view_article.php?id=820
It turns out that this much-feared situation of dynamic invalidity
doesn't come up so much in practice. It's a matter of opinion whether
the absolute safety from such a slim possibility is worth the
reduction of expressiveness. Granted, one can get around many matters
of invariance by declaring a method as generically-typed, but this
increases the complexity of the language and is not a solution for
third-party frameworks.
In the case of frameworks, it's a pity that, given A inheriting from
B and the following framework method:
void DoSomething(IList<Base> list);
One has to call it like this:
IList<B> bList;
// do B-specific stuff
DoSomething((IList<A>)bList);
Which incorporates a cast and dodges type-safety anyway.
One can argue that framework methods accepting generic types should
always have a generic parameter, like this:
void DoSomething<T>(IList<T> list);
Which isn't so bad, but it needlessly propagates pointy brackets
throughout the code and doesn't really make things any clearer. I
would argue that more people would intuitively think that IList<B>
inherits from IList<A> if B inherits from A than that it does not
(and that generic methods are instead required).
Cheers
Marco
P.S. I'm not really trying to pimp my article here; I'm just too lazy
to incorporate everything into this mail.
--
Marco Von Ballmoos
http://earthli.com - Home of the earthli WebCore; PHP web sites made
simple.