Proposal: Contravariant parameter types #3562
Replies: 6 comments
-
I think the main issue is that this feature is quite a lot less useful than covariant return types, especially considering that C# doesn't support overloading on return types, but it does support overloading on parameter types. This means that if you want to have covariant return types in C# 8.0, you can't work around the missing feature by writing e.g.: class Base
{
public virtual Base Clone() { … };
}
class Derived : Base
{
public virtual Derived Clone() { … }
public sealed override Base Clone() => Clone(); // somehow call the other overload here
} But you can quite easily work around missing contravariant parameter types by writing: class TextWriterHandler : StringWriterHandler
{
// Handles broader class of objects, can of course still handle original
public virtual void Handle(TextWriter writer) { … }
public sealed override void Handle(StringWriter writer) => Handle((TextWriter)writer);
} |
Beta Was this translation helpful? Give feedback.
-
Symmetry is not a goal of the language. If the proposal can't provide enough benefit to stand on its own it wouldn't be considered. Contravariant parameters would be a lot more effort for a lot less reward. With return types there is exactly one type that can be covariant which makes the rules that govern the language feature very simple. You can have any number of parameters, each of which being potentially contravariant. Covariant returns have a real impact on the caller of those methods allowing for properly fluent calls without requiring the consumer to interpret and cast the result. There's no such benefit to the caller with contravariant parameters. |
Beta Was this translation helpful? Give feedback.
-
The demand for covariant returns is also consistently far higher than that if contravariance. |
Beta Was this translation helpful? Give feedback.
-
Personally, the only time I would think that this would be actually useful would be delegate relaxation. Otherwise, introducing a new overload with wider parameter types on a derived class, and overriding the original method to forward seems perfectly reasonable. |
Beta Was this translation helpful? Give feedback.
-
@gafter answered about this here
with example here:
|
Beta Was this translation helpful? Give feedback.
-
Would contravariant properties with setters be a possibility, or does it have the same problems? |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
As we all know, the feature of covariant return types will likely be added to C# 9
What about contravariant parameter types, for symmetry? Something like this:
Do you see any issues with a feature like this?
Beta Was this translation helpful? Give feedback.
All reactions