I fought through covariance and contravariance for several days, and I think I understood something, but I was hoping I could get confirmation of this, because I could not get the answer βyesβ or βnoβ through my Current study. I have the following class hierarchy:
class Shape { public string Name { get; set; } } class Square : Shape { }
Then, here is what I started with the program:
List<Square> squares = new List<Square>() { new Square { Name = "Square One" }, new Square { Name = "Square Two" } }; IEnumerable<Square> squaresEnum = squares;
Now I have two questions:
Is the following possible, because IEnumerable <T> IS is covariant:
IEnumerable<Shape> shapesEnumerable = squares;
And, the following is NOT possible, since List <T> is NOT covariant:
List<Shape> shapes = squares;
Here is the complete code, if needed 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; IEnumerable<Shape> shapesEnumerable = squares;
Please, could you tell me if I am on the right track?
source share