New Features in C# 2.0—Co- and Contravariance: What about
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Tutorials |
| C# Tutorials |
| © 2005 O'Reilly Media, Inc. |
What about
contravariance? I get why with covariance I can return a Dog (a Dog is
a Mammal), but why does contravariance work the other way? Shouldn’t it
accept a derived type when it expects a base type?
Contravariance is consistent with Postel’s Law: "Be liberal in what you
accept, and conservative in what you send." As the client, you must make
sure that what you send to the method will work with that method, but
as the implementer of the method you must be liberal and accept the Dog
in any form, even as a reference to its base class.
| Dr. Jonathan Bruce Postel (1943-1998), contributor to Internet
Standards. |
what about reversing the usage of covariance and returning a base
type where a derived type is expected? Can I do that?
No, it works in only one direction. You can, however, return a derived type where a base type is expected.
what about reversing the usage of contravariance and passing in a derived type where a base type is expected?
You can’t do that, either. Again, it works in only one direction. You can, however, pass in a base type where a derived type is expected.
|

