Or is there a better / great way to do this?
If your objects are omitted from the general class, you can save them in one collection. To do something useful with your objects without throwing away type safety, you will need to use a template:
public interface EntityVisitor { void Visit(Arc arc); void Visit(Line line); } public abstract class Entity { public abstract void Accept(EntityVisitor visitor); } public class Arc : Entity { protected double startx; protected double starty; protected double endx; protected double endy; protected double radius; public override void Accept(EntityVisitor visitor) { visitor.Visit(this); } } public class Line : Entity { protected double startx; protected double starty; protected double endx; protected double endy; protected double length; public override void Accept(EntityVisitor visitor) { visitor.Visit(this); } }
After that, you create an instance of EntityVisitor whenever you need to do something useful with your list:
class EntityTypeCounter : EntityVisitor { public int TotalLines { get; private set; } public int TotalArcs { get; private set; } #region EntityVisitor Members public void Visit(Arc arc) { TotalArcs++; } public void Visit(Line line) { TotalLines++; } #endregion } class Program { static void Main(string[] args) { Entity[] entities = new Entity[] { new Arc(), new Line(), new Arc(), new Arc(), new Line() }; EntityTypeCounter counter = entities.Aggregate( new EntityTypeCounter(), (acc, item) => { item.Accept(acc); return acc; }); Console.WriteLine("TotalLines: {0}", counter.TotalLines); Console.WriteLine("TotalArcs: {0}", counter.TotalArcs); } }
And for what it's worth, if you open up for new languages, then F # marked unions + pattern matching are a convenient alternative to the visitor pattern .
source share