Question

Given the following code, I have inherited a class Circle from Shape:

class Shape
{
    void Draw();
}

class Circle : Shape
{
}

void Main(string[] args)
{
    Shape s = new Shape();
    Shape s2 = new Shape();
    Circle c = new Circle();

    List<Shape> ShapeList = new List<Shape>();

    ShapeList.Add(s);
    ShapeList.Add(s2);
    ShapeList.Add(c);
}

How can c be added into the ShapeList?

Was it helpful?

Solution

A Circle is a Shape, because Circle extends Shape. Because of that, you can always treat a Circle object as if it were a Shape since we can be absolutely sure that all of the operations that can be performed on a Shape can also be performed on a Circle.

OTHER TIPS

I believe this is an example of polymorphism. Since Circle is derived from Shape, polymorphism allows us to treat it as it's base type (letting you insert it into a list of type Shape)

Circle extends Shape, which means, it inherits all properties & methods from it. Circle is kind of "superset" of Shape. Considering it you can use it as if it were a Shape. What you can't do is the other way around, namely to insert a shape into a list of Circles. Think of it logically. You have a bunch of Shapes. These can be Circles, Squares, Triangles, etc. But if you have a bunch of Circles, they must specifically be Circles and not a general Shape.

Leave the programming part, logically every circle, rectangle.. everything is a shape. Its just like you are making a list of contacts in your Phone. Some contacts have a T-mobile connection, some use Vodafone, some use Orange, but all are phones and you add them in your list in exactly same manner without any difference. You can take this list to apply polymorphism as well by calling different contacts: Your calling mechanism will be exactly same but on the run-time (calling) it will be decided which phone service did this contact have.

This is about covariance and contravariance in generics. See http://msdn.microsoft.com/en-us/library/dd799517.aspx to get some concept about that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top