Suppose there are 3 different classes, A (parent) and two heirs B and C.
public class A { ... }; public class B : A { ... }; public class C : A { ... }; This is a simplified scheme, the hierarchy may be more complicated, B and C may have heirs, etc. And the question is, how best to approach the architectural solution for working with lists in which classes from this hierarchy can appear.
For example, there are lists and a method that adds class B and class C to the list, and accordingly, for each individual list + the general list for A. It looks like this:
public List<A> AList = new List<A>(); public List<B> BList = new List<B>(); public List<C> CList = new List<C>(); public void Add_B(B obj) { AList.Add(obj); BList.Add(obj); } public void Add_C(C obj) { AList.Add(obj); CList.Add(obj); } Is this generally the correct solution? The more classes are involved in the hierarchy, the more it turns into spaghetti from the lists, it also puts pressure on the RAM, but in some sense it is easier to work with the necessary classes. On the other hand, we consider the option of adding only to AList, and using "is" to determine the desired type and work with it, but does this affect the performance? What other options are there for building work with arrays of parent-heir objects with which work can be done individually or with all at once?
public Dictionary<object, MyClass> Dict = new Dictionary<object, MyClass>();? or as @VladimirT noticed use interfaces. - Digital Core