I have two classes an Arc class and a Line class
public class Arc
{
protected double startx;
protected double starty;
protected double endx;
protected double endy;
protected double radius;
public Arc(){}
}
public class Line
{
protected double startx;
protected double starty;
protected double endx;
protected double endy;
protected double length;
public Line(){}
}
But I want to store arcs and lines in the same list, so I tried an interface like this
public interface Entity
{
double StartX();
double StratY();
double EndX();
double EndY();
}
Then I added the appropriate methods to each class and added the code to use the interface. Now I can add both types of objects to a list, but I want to get the length from a line object and don’t want to add a length method to the arc or the interface. Is my only option to cast the line object back to a line object like this?
List<Entity> entities = new List<Entity>();
entities.Add(new Line(10,10,5,5));
Line myLine = (Line)Entities[0]
double length = myLine.Length();
*Assuming I have all the proper methods in the line class.
Or is there a better/different way to do this?
If your objects descend from a common class, then you can store them in the same collection. In order to do anything useful with your objects without throwing away type safety, you’d need to implement the visitor pattern:
Once that’s in place, you create an instance of EntityVisitor whenever you need to do something useful with your list:
And for what its worth, if your open to trying new languages, then F#’s tagged unions + pattern matching are a handy alternative to the visitor pattern.