开发者

Simple examples of co and contravariance

Could someone provide me simple C# examples of convariance, contravariance, invariance and contra-invariance (if such thing exi开发者_运维问答sts).

All samples I've seen so far was just casting some object into System.Object.


Could someone provide me simple C# examples of convariance, contravariance, invariance and contra-invariance (if such thing exists).

I have no idea what "contra-invariance" means. The rest are easy.

Here's an example of covariance:

void FeedTheAnimals(IEnumerable<Animal> animals) 
{ 
    foreach(Animal animal in animals)
        animal.Feed();
}
...
List<Giraffe> giraffes = ...;
FeedTheAnimals(giraffes);

The IEnumerable<T> interface is covariant. The fact that Giraffe is convertible to Animal implies that IEnumerable<Giraffe> is convertible to IEnumerable<Animal>. Since List<Giraffe> implements IEnumerable<Giraffe> this code succeeds in C# 4; it would have failed in C# 3 because covariance on IEnumerable<T> did not work in C# 3.

This should make sense. A sequence of Giraffes can be treated as a sequence of Animals.

Here's an example of contravariance:

void DoSomethingToAFrog(Action<Frog> action, Frog frog)
{
    action(frog);
}
...
Action<Animal> feed = animal=>{animal.Feed();}
DoSomethingToAFrog(feed, new Frog());

The Action<T> delegate is contravariant. The fact that Frog is convertible to Animal implies that Action<Animal> is convertible to Action<Frog>. Notice how this relationship is the opposite direction of the covariant one; that's why it is "contra" variant. Because of the convertibility, this code succeeds; it would have failed in C# 3.

This should make sense. The action can take any Animal; we need an action that can take any Frog, and an action that can take any Animal surely can also take any Frog.

An example of invariance:

void ReadAndWrite(IList<Mammal> mammals)
{
    Mammal mammal = mammals[0];
    mammals[0] = new Tiger();
}

Can we pass an IList<Giraffe> to this thing? No, because someone is going to write a Tiger into it, and a Tiger cannot be in a list of Giraffes. Can we pass an IList<Animal> into this thing? No, because we are going to read a Mammal out of it, and a list of Animals might contain a Frog. IList<T> is invariant. It can only be used as what it actually is.

For some additional thoughts on the design of this feature, see my series of articles on how we designed and built it.

http://blogs.msdn.com/b/ericlippert/archive/tags/covariance+and+contravariance/


Invariance(in this context) is the absence of both co- and contra-variance. So the word contra-invariance doesn't make sense. Any type parameter that's not tagged as either in or out is invariant. This means this type parameter can both be consumed and returned.

A good example of co-variance is IEnumerable<out T> because an IEnumerable<Derived> can be substituted for an IEnumerable<Base>. Or Func<out T> which returns values of type T.
For example an IEnumerable<Dog> can be converted to IEnumerable<Animal> because any Dog is an animal.

For contra-variance you can use any consuming interface or delegate. IComparer<in T> or Action<in T> come to my mind. These never return a variable of type T, only receive it. Wherever you expect to receive a Base you can pass in a Derived.

Thinking of them as input-only or output-only type-parameters makes it easier to understand IMO.

And the word invariants is typically not used together with type variance, but in the context of class or method invariants, and represents a conserved property. See this stackoverflow thread where the differences between invariants and invariance are discussed.


If you consider the regular use of generics, you regularly use an interface to handle an object, but the object is an instance of a class - you can't instantiate the interface. Use a simple list of strings as an example.

IList<string> strlist = new List<string>();

I'm sure you're aware of the advantages of using an IList<> rather than directly using a List<>. It allows for inversion of control, and you might decide you don't want to use a List<> any longer, but you want a LinkedList<> instead. The above code works fine because the generic type of both the interface and class is the same: string.

It can get a bit more complicated if you want to make a list of list of string though. Consider this example:

IList<IList<string>> strlists = new List<List<string>>();

This clearly won't compile, because the generic types arguments IList<string> and List<string> are not the same. Even if you declared the outer list as a regular class, like List<IList<string>>, it would not compile - the type arguments do not match.

So here's where covariance can help. Covariance allows you to use a more derived type as the type argument in this expression. If IList<> was made to be covariant, it would simlpy compile and fix the problem. Unfortunately, IList<> is not covariant, but one the interfaces it extends is:

IEnumerable<IList<string>> strlists = new List<List<string>>();

This code now compiles, the type arguments are the same as they were above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜