A collection of derived classes that have a common base class

Say I have several derived classes whose base class is a common class. Each derived class inherits a base class with a specific type override (but all types are also inferred from the same base type).

For instance:

I have a baseline class

class RowBase { //some properties and abstract methods } 

And I have two specific string classes that are derived from the base string class

 class SpecificRow1 : RowBase { //some extra properties and overrides } class SpecificRow2 : RowBase { //some extra properties and overrides } 

Then I have a second base class, which is a generic class that contains a set of derived classes from RowBase

 class SomeBase<T> where T : RowBase { ICollection<T> Collection { get; set; } //some other properties and abstract methods } 

Then I have two classes that come from SomeBase but use different class classes

 class SomeClass1 : SomeBase<SpecificRow1> { //some properties and overrides } class SomeClass2 : SomeBase<SpecificRow2> { //some properties and overrides } 

Now that in my main or larger area I want to create a list / collection consisting of SomeClass1 and SomeClass2 objects. how

 ICollection<???> CombinedCollection = new ... CombinedCollection.Add(new SomeClass1()) CombinedCollection.Add(new SomeClass2()) . . . //add more objects and do something about the collection . . . 

Question: is it possible to have such a collection? If possible, how can I achieve this? If not, what could be an alternative way?

+4
source share
1 answer

This can be done using covariance and contravariance .

Add a new interface and make the covariance parameter T (using the out keyword):

 interface ISomeRow<out T> where T : RowBase { } 

SomeBase should inherit this interface as follows:

 class SomeBase<T> : ISomeRow<T> where T : RowBase { //some other properties and abstract methods } 

Then the following will work:

 List<ISomeRow<RowBase>> myList = new List<ISomeRow<RowBase>>(); myList.Add(new SomeClass1()); myList.Add(new SomeClass2()); 

Hope this is what you are looking for :)

+5
source

Source: https://habr.com/ru/post/1444685/


All Articles