ASP.NET 4.0 - Variance

by Edward 12 June 2009 08:28

An aspect of generics that often comes across as surprising is that the following is illegal:

IList<string> strings = new List<string>();
IList<object> objects = strings;

The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this.

If it were allowed you could write:

objects[0] = 5;
string s = strings[0];

Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.

However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:

IEnumerable<object> objects = strings;

There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element in. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.

Here is an example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace SimpleVariance

{

    class Animal { }

    class Cat: Animal { }

 

    class Program

    {

        // To understand what the new CoVariance and ContraVariance code does for you

        // Try deleting or adding the words out and in from the following 2 lines of code:

        delegate T Func1<out T>();

        delegate void Action1<in T>(T a);

       

        static void Main(string[] args)

        {

            Func1<Cat> cat = () => new Cat();

            Func1<Animal> animal = cat;

 

            Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };

            Action1<Cat> cat1 = act1;

 

            Console.WriteLine(animal());

            cat1(new Cat());

        }       

    }

}

 

Tags: , , ,

ASP.NET | Other

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List