M
M
Mikhail32022-03-03 19:57:40
C++ / C#
Mikhail3, 2022-03-03 19:57:40

When to use Covariance and Contravariance?

I still do not understand where Covariance and Contravariance can be applied. Can someone explain? In which cases ?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
freeExec, 2022-03-03
@freeExec

Return the most specific type from the method, and take the most general type in the arguments.

S
Stanislav Makarov, 2022-03-03
@Nipheris

https://en.wikipedia.org/wiki/Covariance_and_contr...

For example, in C#, if Cat is a subtype of Animal, then:
  • IEnumerable<Cat>is a subtype of IEnumerable<Animal>. The subtyping is preserved because IEnumerable<T>is covariant on T.
  • Action<Animal>is a subtype of Action<Cat>. The subtyping is reversed because Action<T>is contravariant on T.

I don't even know what to add.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question