Reputation: 3317
Is there a collection in c# that supports the inheritance like concept that objects can have of appearing to include all the elements from another as well as themselves?
For example:
HashSet<animal> animals = new HashSet<animal>();
HashSet<dog> dogs = new HashSet<dog>();
animals.also_appears_to_include(dogs);
So if I for example added 2 elements to dogs and 1 to animals, then looked at how many elements animals has I would see 3.
Alternatively I could put references to the above mentioned 3 elements in each, giving animals 3 elements and dogs 2. I'd still have the two separate, overlapping lists which is desirable, however adding and removing elements could become tricky, in this simple example having to add or remove from both collections in the case of adding and removing dogs.
Or I could implement my own collection with this functionality.
Upvotes: 2
Views: 1430
Reputation: 39695
Let dogs and cats inherit from an interface, and create HashSet's of the interface instead of the classes. Or use a base class.
for example:
HashSet<IAnimal>
Upvotes: 2
Reputation: 3485
Thats not that tricky
// Adding
Animals.Add( animal );
if( animal is dog )
Dogs.Add( animal );
//Removing
Dogs.Remove( animal );
Animals.Remove( animal );
Upvotes: 1
Reputation: 41757
There is nothing provided by MS that can achieve your functionality, however
You could just keep a set of animal and use linq to filter it on the fly:
var animals = new HashSet<Animal>();
var dogs = animals.OfType<Dog>();
Upvotes: 5