Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - list of subclass Types

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.

like image 795
orion elenzil Avatar asked Oct 27 '25 10:10

orion elenzil


1 Answers

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)).

like image 80
Matt Thomas Avatar answered Oct 30 '25 01:10

Matt Thomas