I have a simple interface ElementContainer (which is also an element) which holds a list with Elements in it:
interface IElementContainer : IElement
{
List<Element> Elements { get; }
}
Now I have a class implementing this interface:
class ConcreteContainer : IElementContainer
{
List<IElement> Elements { get; private set; }
}
But I don’t want the class to be a container for all Elements but only for a subset of them, say SpecificElement, however this is not possible (ofcourse):
class SpecificElementContainer : IElementContainer
{
List<SpecificElement> Elements { get; private set; }
}
Therefore I thought of something like:
class SpecificElementContainer : IElementContainer
{
List<IElement> Elements { get; private set; }
List<SpecificElement> SpecificElements
{
get
{
return return Elements.FindAll(el => el is T).Select<IElement, T>(el => (T)el).ToList<T>();
}
}
But this way I can not do something like: SpecificContainer.SpecificElements.Add(...) since it not added to the Elements. And besides that… it smells fishy to do it like this.
Any clues how to restructure this in a sane way?
Edit after Jon Skeet’s answer
Reading Jons comment my problem is actually a little more complicated than I showed above but I forgot some very important information.
When I have a class which implements the above interface and the elements list is filled like this:
Elements = { ConcreteElementA, ConcreteElementA, ConcreteElementC, ConcreteElementB }
What I would like is that I could do this ConcreteContainer.ConcreteElementCs.Add(new ConcreteElementC()) which would result in:
Elements = { ConcreteElementA, ConcreteElementA, ConcreteElementC, ConcreteElementB, ConcreteElementC }
Additional edit
After some confusion I want to rephrase my question as follows:
I have a collection List<Element> OriginalCollection. I want to create a subset collection with elements which implement Element, ConcreteElement, List<ConcreteElement> Subset and add to that in such a way that OriginalCollection is also modified.
It sounds like your
ElementContainerinterface should be generic:Then: