Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Derived Class object is added to Base Class objects List

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?

like image 248
Failed Scientist Avatar asked Feb 20 '13 17:02

Failed Scientist


1 Answers

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.

like image 173
Servy Avatar answered Oct 25 '22 01:10

Servy