New Features in C# 2.0—Gain Flexibility with Delegate Covariance and Contravariance

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

Gain Flexibility with Delegate Covariance and Contravariance

Now it is legal to provide a delegate method with a return type that is derived (directly or indirectly) from the delegate’s defined return type; this is called covariance. That is, if a delegate is defined to return a Mammal, it is legal to use that delegate to encapsulate a method that returns a Dog if Dog derives from Mammal and a Retriever if Retriever derives from Dog which derives from Mammal.

Similarly, now it is legal to provide a delegate method signature in which one or more of the parameters is derived from the type defined by the delegate. This is called contravariance. That is, if the delegate is defined to take a method whose parameter is a Dog you can use it to encapsulate a method that passes in a Mammal as a parameter, if Dog derives from Mammal.


Covariance allows you to encapsulate a method with a return type that is directly or indirectly derived from the delegate’s return type.


Previous_Page_.gif Next_Page_.gif

Personal tools