I'm given classes ContainerA
, ContainerB
, ElementA
and ElementB
. I can't modify these classes because of very-good-reasons™ with the exception that I can add interfaces.
What I would like is something like the IElements
interface (expect legal) as it would allow me to easily loop over the elements and read properties from the elements of either ContainerA
or ContainerB
without knowing which concrete implementation is actually used. There are no methods on any of the classes. For the element classes I only need to access properties implemented by the ElementA
, exemplified by the Id
property.
What are my options?
public interface IElements
{
List<ElementA> Elements { get; set; }
}
public class ContainerA : IElements
{
public List<ElementA> Elements { get; set; }
}
public class ContainerB : IElements
{
public List<ElementB> Elements { get; set; }
}
public class ElementA
{
public string Id { get; set; }
}
public class ElementB : ElementA
{
}
I hope to achieve something similar to:
IElements container = ...;
foreach (var element in container.Elements)
{
Console.WriteLine(element.Id);
}