C # - list of subclass types

I would 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 would like to constrain the list to only accept subclasses of MyClass.

This is different from questions like this . Ideally I would like to avoid linq as it is not currently used in my project.

+3


source to share


2 answers


Service 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));
    }
}

      

Using:

var x = new ListOfTypes<SuperClass>();
x.Add<MySubClass>()

      



Note that you can make this class an implemented interface, for example IReadOnlyList<Type>

, if you want to expose other code to access the contained one Type

, if other code should not depend on that class.

But if you want to inherit anyway, you can create your own class that inherits from List

and then add your own generic method Add

like this:

public class ListOfTypes<T> : List<Type>
{
    public void Add<U>() where U : T
    {
        Add(typeof(U));
    }
}

      

Just know what Lee said : with this second version, you can still Add(typeof(Foo))

.

+3


source


You must get the list class from the list and override the Add method to do the required type checking. I don't know how to do this automatically in .NET.

Something like this might work:



public class SubTypeList : List<System.Type>
{
    public System.Type BaseType { get; set; }

    public SubTypeList()
        : this(typeof(System.Object))
    {
    }

    public SubTypeList(System.Type baseType)
    {
        BaseType = BaseType;
    }

    public new void Add(System.Type item)
    {
        if (item.IsSubclassOf(BaseType) == true)
        {
            base.Add(item);
        }
        else
        {
            // handle error condition where it not a subtype... perhaps throw an exception if
        }
    }
}

      

You will need to update other methods that add / update items to the list (index installer, AddRange, Insert, etc.)

+1


source







All Articles