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?

  • Perhaps your logic can be built much easier. Most likely you only need an interface, you just do not use it. Perhaps you need to use patterns that make life easier for you. It would not be bad for you to explain why you need so many lists, maybe there is another way, not to use sets. and go different. - Monomax
  • Why not use public Dictionary<object, MyClass> Dict = new Dictionary<object, MyClass>(); ? or as @VladimirT noticed use interfaces. - Digital Core
  • @VladimirT interface will not go, because the logic is built as you move through the hierarchy. Regarding the set of lists, there is a third-party class that conducts large-scale work with the entire hierarchy, including counting the number of objects of each class, obtaining data, launching their unique methods, etc. - Veles
  • one
    it is still not clear why your classes cannot have interfaces, and why you don’t want to work on them, it’s simpler and more convenient, then you will have, just working out for uniqueness, each interface can only have its own unique methods. - Monomax
  • Load on the operational will not be if it is a list of classes. In fact, the lists of classes do not store the objects themselves, but references to them, therefore, if you add them to two lists at once, the size in RAM will increase slightly. And the task that you want to solve so is to be voiced, since you ask how in this case it is better to work with lists. - John

0