John Tan
John Tan

Reputation: 1385

Accessing the derived class object inside a base classed list

Say I have 3 classes:

class Geometry
{ ... }

class Line : Geometry
{ ... }

class Circle : Geometry
{ ... }

And I want to put all the objects of Line and Circle class into a common list, like so:

List<Geometry> list = new List<Geometry>();
Line line = new Line();
Circle circle = new Circle();
list.Add(line);
list.Add(circle);

My question is that is it allowed? Is it still possible to retrieve the derived class from the list like so:

Line newLine = (Line)list[0];
Circle newCircle = (Circle)list[1];

If not, then is there a good way to store all these different types of objects under the same list?

Upvotes: 0

Views: 215

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

How about this:

List<Geometry> list = new List<Geometry>(); 
Geometry line = new Line(); 
Geometry circle = new Circle(); 
list.Add(line); 
list.Add(circle);

and when fetching use OfType() to get desired type object(s):

List<Line> lines = list.OfType<Line>().ToList(); // get lines
List<Circle> circles = list.OfType<Circle>().ToList(); // get circles

Upvotes: 2

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Yes, it's allowed since Line and Circle are Geometry:

  List<Geometry> list = new List<Geometry>() {
    new Line(),
    new Circle()
  };

You'd rather check if Geometry is Line, Circle etc:

  Line newLine = list[0] as Line;       // Line instance or null
  Circle newCircle = list[1] as Circle; // Circle instance or null

To extract all, say, Line's use Linq:

  List<Line> lines = list.OfType<Line>().ToList();

Upvotes: 1

Christos
Christos

Reputation: 53958

Of course you can store them this way. Since all your objects has a common base, the Geometry object, this is fine.

Then when you retrieve them from the list I would suggest you use the as operator, like below:

Line newLine = list[0] as Line;

I would suggest so, because as it is stated in MSDN:

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception. Consider the following example:

Upvotes: 1

Related Questions