Information Technology Reference
In-Depth Information
ICovariantDelegate interface means that it is actually a means by which T
objects are returned from an ICovariantDelegate<T> implementing
object. It may look like it should be contravariant, but it is covariant with
respect to the interface.
IContravariantDelegate<T> is similar but shows how you can use dele-
gates in a contravariant interface. Again, the ActOnAnItem method should
be obvious. The ActOnAnItemLater() method is just a little more com-
plicated. You're returning a method that will accept a T object sometime
later. That last method, once again, may cause some confusion. It's the
same concept as with the other interface. The GetAnItemLater() method
accepts a method that will return a T object sometime later. Even though
Func<out T> is declared covariant, its use is to bring an input to the object
implementing IContravariantDelegate. Its use is contravariant with respect
to the IContravariantDelegate.
It certainly can get complicated describing exactly how covariance and
contravariance work. Thankfully, now the language supports decorating
generic interfaces and delegates with in (contravariant) and out (covari-
ant) modifiers. You should decorate any interfaces and delegates you define
with the in or out modifiers wherever possible. Then, the compiler can
correct any possible misuses of the variance you've defined. The compiler
will catch it both in your interface and delegate definitions, and it will
detect any misuse of the types you've created.
 
Search WWH ::




Custom Search