Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C# do "simple" type inference on generics?

Just curious: sure, we all know that the general case of type inference for generics is undecidable. And so C# won't do any kind of sub-typing at all: if Foo<T> is generic, Foo<int> isn't a subtype of Foo<T>, or Foo<Object> or of anything else you might cook up. And sure, we all hack around this with ugly interface or abstract class definitions.

But... if you can't beat the general problem, why not just limit the solution to cases that are easy. For example, in my list above, it is OBVIOUS that Foo<int> is a subtype of Foo<T> and it would be trivial to check. Same for checking against Foo<Object>.

So is there some other deep horror that would creep forth from the abyss if they were to just say, aw shucks, we'll do what we can? Or is this just some sort of religious purity on the part of the language guys at Microsoft?


Update:

This is a very old thread. These days, C# has var, which solves half of what I complained about, and then using the Linq style of anonymous delegates, has a great notation for not needing to type in the same stuff twice. So every aspect of what I was objecting to has been resolved by more recent changes to C# (or perhaps it simply took me a while to learn about things that were just being introduced around when I posted the thread...) I use these new features now in the Isis2 system for reliable cloud computing (isis2.codeplex.com) and I think the library has a very clean look and feel as a result. Check it out and let me know what you think). -- Ken Birman (July 2014)

like image 924
Ken Birman Avatar asked Dec 21 '10 20:12

Ken Birman


1 Answers

They already have solved it for many of the "easy" cases: C# 4.0 supports covariance and contravariance for generic type parameters in interfaces and delegates. But not classes unfortunately.

It's fairly easy to workaround this limitation:

List<Foo> foos = bars.Select(bar => (Foo)bar).ToList();
like image 52
Mark Byers Avatar answered Sep 26 '22 16:09

Mark Byers