Given public class BaseClass
that has derived classes, where a number of those follow the form
public class DerivedClass : BaseClass, ISpecificInterface
is there a way of specifying a collection that applies to just the derived classes that implement that interface?
For example, something like
public List<BaseClass where ISpecificInterface> myList; or
public List<BaseClass : ISpecificInterface> myList;
You can only constrain generic parameters, not generic arguments. So you'll need:
You may want to inherit
List<T>for this instead:And then you can use it as property type:
Point being: you can only declare the list as containing one type. So if you want a list that can hold any class derived from
BaseClassand implementingISpecificInterface, you must do so in a method:You could then combine this:
But now someone can cast your DerivedList to
IList<ISpecificInterface>and callAdd()on that, with an object implementingISpecificInterfacebut not inheriting fromBaseClass.