I often forget if i have to use in or out when defining covarient and contravarient generic types. In java i have the mnemonic PECS (producer extends consumer super) to help me. Do you know a similar mnemonic for c#?
+3
A:
Didn't they do this for us when they called them 'in' and 'out' rather than covariant and contravariant? Just think: am I pushing values 'in', or getting them 'out'? If unsure, try 'out' - it is far more common (and easier to understand).
Marc Gravell
2010-08-27 16:29:39
Although this is true, it is not very catchy.
mR_fr0g
2010-09-01 14:10:45
A:
When I don't remember, I always refer to IEnumerable<out T>
(which means of course I have to remember the signature of that interface...). You can only get instances of T "out" of an IEnumerable<out T>
, so it is covariant. If you can only pass instances of T "in" to an interface (or delegate, which is more common), it's contravariant.
Thomas Levesque
2010-08-27 17:04:47
A:
in
types are passed in
to functions; out
types are returned out
from functions.
Gabe
2010-08-27 17:28:25
This is not what mR_fr0g has asked for. He wants a mnemonic for in and out when used as generic class variance type modifiers (which is a new funcionality of C# 4.0), not the common, old usage on method parameters.
rsenna
2010-08-27 19:10:53
rsenna: That's exactly what rsenna asked for. When creating a generic interface, types that are only passed in to functions can get the `in` label and types that are only returned from functions can get the `out` label. Types that are both passed in and returned (or used as `ref` or `out` parameters) are invariant and can't get either label.
Gabe
2010-08-27 19:36:00