I'd like to have a List of Class Types (not a list of Class instances) where each member of the List is a Subclass of MyClass.
For example, i can do this:
List<System.Type> myList;
myList.Add(typeof(mySubClass));
but i'd like to restrict the list to only accept subclasses of MyClass.
This is distinct from questions like this. Ideally i'd like to avoid linq, as it's currently unused in my project.
Servy is right in his comment, and Lee in his: it's much more preferable to compose than inherit. So this is a good option:
public class ListOfTypes<T>
{
    private List<Type> _types = new List<Type>();
    public void Add<U>() where U : T
    {
        _types.Add(typeof(U));
    }
}
Usage:
var x = new ListOfTypes<SuperClass>();
x.Add<MySubClass>()
Note that you can make this class implement an interface like IReadOnlyList<Type> if you want to give other code read access to the contained Types without other code having to depend on this class.
But if you want to inherit anyway, you could create your own class that inherits from List, then add your own generic Add method like this:
public class ListOfTypes<T> : List<Type>
{
    public void Add<U>() where U : T
    {
        Add(typeof(U));
    }
}
Just be aware of what Lee said: with this second version you can still Add(typeof(Foo)).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With