Please assist in confirming if my understanding of covariance here is correct?

Viewed 120

I have been battling through covariance and contravariance for a few days now and I think I have understood something but I was hoping that I could get confirmation on this as I haven't been able to get a yes or no answer through my current research. I have the following class hierarchy:

class Shape
{
    public string Name { get; set; }
}
class Square : Shape
{

}

Then, this is what I what I started off the program with:

List<Square> squares = new List<Square>() { new Square { Name = "Square One" }, new Square { Name = "Square Two" } };
IEnumerable<Square> squaresEnum = squares;

Now are the two questions I have:

Is the following possible because IEnumerable< T > IS covariant:

IEnumerable<Shape> shapesEnumerable = squares;

AND, is the following NOT possible because List< T > is NOT covariant:

List<Shape> shapes = squares;

Here is the full program code if it is required for anything:

class Program
{
    static void Main(string[] args)
    {
        List<Square> squares = new List<Square>() { new Square { Name = "Square One" }, new Square { Name = "Square Two" } };
        IEnumerable<Square> squaresEnum = squares;

        /* Does this work because IEnumerable<T> is covariant? */
        IEnumerable<Shape> shapesEnumerable = squares;

        /* Does this NOT work because List<T> is NOT covariant */
        //List<Shape> shapes = squares;

        Console.ReadKey();
    }
}
class Shape
{
    public string Name { get; set; }
}
class Square : Shape
{

}

Please could you let me know if I'm on the right track with this?

2 Answers
Related