Covaraint return types in C#
No, they are not supported, but you can achieve the same functionality using generic interfacesOne of the attendees at VS Developer Connections yesterday asked about covariant return types in C# during the “Ask the Experts” panel. I said they were not supported, but I’d look it up again to verify. I did remember correctly: C# (all versions to date) does not support covariant return types.
Backing up just a bit, let me explain covariant return types. The following is legal C++ (which does support covariant return types):
class B
{
public:
virtual B ProduceObject()
{
return new B();
}
};
class D: B
{
public:
virtual D ProduceObject()
{
return new D();
}
}
Notice that the return type of D::ProduceObject does not match the return type of B::ProduceObject. It is a valid derived class, but it is not the same type.
A similar construct in C#, would not compile:
public class B
{
public virtual B getThing()
{
return null;
}
}
public class D : B
{
public override D getThing() // Illegal C#
{
return null;
}
}
But there is a way to get a similar affect. You can use generic interfaces to define the functionality you want, and a specialization of the interface implementation can provide the proper function:
public interface Producer<T>
{
T getThing();
}
public class D : Producer <D>
{
public D getThing()
{
return null;
}
}
No, this does not solve every use case for covariant types, and there are some differences. The example I showed above places no restrictions on the type that implements the producer interface. That’s very broad for most uses of covariant return types. However, by extending the Producer interface with the other functionality you desire, or by adding constraints on T, you could get the same functionality that you achieve with covariant types in C++ (or other languages).