Does anyone know why covariant return types are not supported in C#? Even when attempting to use an interface, the compiler complains that it is not allowed. See the followi
UPDATE: This answer was written in 2011. After two decades of people proposing return type covariance for C#, it looks like it will finally be implemented; I am rather surprised. See the bottom of https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/ for the announcement; I'm sure details will follow.
First off, return type contravariance doesn't make any sense; I think you are talking about return type covariance.
See this question for details:
Does C# support return type covariance?
You want to know why the feature is not implemented. phoog is correct; the feature is not implemented because no one here ever implemented it. A necessary but insufficient requirement is that the feature's benefits exceed its costs.
The costs are considerable. The feature is not supported natively by the runtime, it works directly against our goal to make C# versionable because it introduces yet another form of the brittle base class problem, Anders doesn't think it is an interesting or useful feature, and if you really want it, you can make it work by writing little helper methods. (Which is exactly what the CIL version of C++ does.)
The benefits are small.
High cost, small benefit features with an easy workaround get triaged away very quickly. We have far higher priorities.
Eric Lippert has written a few posts on this site about return method covariance on method overrides, without as far as I can see addressing why the feature is unsupported. He has mentioned, though, that there are no plans to support it: https://stackoverflow.com/a/4349584/385844
Eric is also fond of saying that the answer to "why isn't X supported" is always the same: because nobody has designed, implemented, and tested (etc.) X. An example of that is here: https://stackoverflow.com/a/1995706/385844
There may be some philosophical reason for the lack of this feature; perhaps Eric will see this question and enlighten us.
EDIT
As Pratik pointed out in a comment:
interface IBuilder<in T>
{
T Build();
}
should be
interface IBuilder<out T>
{
T Build();
}
That would allow you to implement PastryOrder : IBuilder<PastryOrder>
, and you could then have
IBuilder<Order> builder = new PastryOrder();
There are probably two or three approaches you could use to solve your problem, but, as you note, return method covariance is not one of those approaches, and none of this information answers the question of why C# doesn't support it.
The contravariant generic parameter cannot be output, because that cannot be guaranteed to be safe at compile time, and C# designers made a decision not to prolong the necessary checks to the run-time.
This is the short answer, and here is a slightly longer one...
Variance is a property of a transformation applied to a type hierarchy:
In C#, the "transformation" is "being used as a generic parameter". For example, let's say a class Parent
is inherited by class Child
. Let's denote that fact as: Parent
> Child
(because all Child
instances are also Parent
instances, but not necessarily the other way around, hence Parent
is "bigger"). Let's also say we have a generic interface I<T>
:
I<Parent>
> I<Child>
, the T is covariant (the original "direction" between Parent
and Child
is kept).I<Parent>
< I<Child>
, the T is contravariant (the original "direction" is reversed).I<Parent>
is unrelated to I<Child>
, the T is invariant.If C# compiler actually agreed to compile the following code...
class Parent {
}
class Child : Parent {
}
interface I<in T> {
T Get(); // Imagine this actually compiles.
}
class G<T> : I<T> where T : new() {
public T Get() {
return new T();
}
}
// ...
I<Child> g = new G<Parent>(); // OK since T is declared as contravariant, thus "reversing" the type hierarchy, as explained above.
Child child = g.Get(); // Yuck!
...this would lead to a problem at run-time: a Parent
is instantiated and assigned to a reference to Child
. Since Parent
is not Child
, this is wrong!
The last line looks OK at compile-time since I<Child>.Get
is declared to return Child
, yet we could not fully "trust" it at run-time. C# designers decided to do the right thing and catch the problem completely at compile-time, and avoid any need for the run-time checks (unlike for arrays).
(For similar but "reverse" reasons, covariant generic parameter cannot be used as input.)
Just to post this somewhere google finds it... I was looking into this because I wanted to have an interface in which I can return collections / enumerables of arbitrary classes implementing a specific interface.
If you're fine with defining the concrete types you want to return, you can simply define your interface accordingly. It will then check at compile time that the constraints (subtype of whatever) are met.
I provided an example, that might help you.
As Branko Dimitrijevic pointed out, usually it is unsafe to allow covariant return types in general. But using this, it's type-safe and you can even nest this (e. g. interface A<T, U> where T: B<U> where U : C
)
(Disclaimer: I started using C# yesterday, so I might be completely wrong regarding best practices, someone with more experience should please comment on this :) )
Example:
Using
interface IProvider<T, Coll> where T : ProvidedData where Coll : IEnumerable<T>
{
Coll GetData();
}
class XProvider : IProvider<X, List<X>>
{
List<X> GetData() { ... }
}
calling
new XProvider().GetData
works and in this case is safe. You only have to define the types you want to return in this case.
More on this: http://msdn.microsoft.com/de-de/library/d5x73970.aspx