Contravariant general modifier in

public interface IOInitializable<in ItemType> 

What is contravariant: the transformation from a narrower (circle) to a wider (figures)

mean for the interface?

What are the consequences and dangers?

I read http://msdn.microsoft.com/en-us/library/dd469484.aspx , but that does not help me.

+4
source share
2 answers

I would recommend reading this explanation from Tomas:

The theory of covariance and contravariance in C # 4

It boils down to the fact that if you have a method call that passes multiple β€œCircles,” you can use a function that takes several β€œshapes” if it doesn't return a β€œShape” (because it may or may not be β€œ Around ").

+3
source

IComparer is a good example demonstrating this. IComparer looks like this:

 IComparer<in T> 

Take the following:

 IComparer<Primate> IComparer<Chimpanzee> 

where is Chimpanzee : Primate (of course). A method that requires IComparer<Chimpanzee> can take IComparer<Primate> as an argument, because if the comparer can compare primates, it can also compare chimpanzees, since it uses common features for the two types that affect the comparison .

A good way to think about it is in terms of functionality. Covariance allows you to transfer more complex objects that implement basic functionality (for example, passing a string to an object). Contravariance does something similar ... comparing all primates is more complicated than just comparing chimpanzees. It allows you to replace a comparator of a certain type with one that compares a more general type. In this sense, "in" refers more to the functionality of the method than to the actual type passed.

+3
source

Source: https://habr.com/ru/post/1446406/


All Articles