Given a class and a subclass
public class Base
{
public string Name { get; set; }
}
public class Derived : Base
{
public string Extra {get; set; }
}
and a generic list
var list = new List<Base>();
I want to prevent this:
var b = new Base { Name = "base" };
var d = new Derived { Name = "derived", Extra = "stuff" };
list.Add(b); // this is good
list.Add(d); // this is BAD
The reason for wanting to prevent this is the list will be serialized in a way that loses type information, then reserialized to List<Base>
. Any items that derive frome Base
will require downcasting to a type unknown by the deserializer (I certainly don't want use reflection to find a class that inherits from Base and has an 'Extra' property). Perhaps I will wrestle with approaches to solve that and that may lead to another question. But for now, can I avoid the problem by preventing derived objects from being added to a generic list?