views:

107

answers:

3

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
Although this is true, it is not very catchy.
mR_fr0g
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
A: 

in types are passed in to functions; out types are returned out from functions.

Gabe
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
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