I am currently struggling with a class design involving generic lists:
Code says more than thousand words:
class Document
{
public List<Result> Results { get; } = new List<Result>();
}
class Result
{
}
class SpecialDocument : Document
{
public new List<SpecialResult> Results { get; } = new List<SpecialResult>();
}
class SpecialResult : Result
{
}
What I don't like of the current design is that SpecialDocument.Results
hides Document.Results
. If one has the Document
view on a SpecialDocument
, there are no results at all, even there could be the Result
view of all SpecialResult
elements.
What I would like to accomplish is:
SpecialDocument doc = new SpecialDocument();
doc.Results.Add(new SpecialResult());
Assert.AreEqual(1, (doc as Document).Results.Count); // Here my design obviously fails right now
... I'd like to accomplish that without loosing type safety (as that's actually the reason for List<T>
not being covariant).
Edit
I forgot to mention that SpecialDocument
and Document
actually need to have the same successor (or implement the same interface), such that they can coexist within one collection:
List<Document> documents = new List<Document>()
{
new Document(),
new SpecialDocument()
};
Document
genericwhere T : Result