Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# list of "Type" that implements specific interface

I want to create a List<System.Type> listOfTypesOfGlasses , where Type must implement a specific interface IGlass , so I could load it with Types of glasses. Is there a way to enforce in compile time this constraint(must implement IGlass) ?

like image 249
Yoav R. Avatar asked Nov 06 '25 09:11

Yoav R.


1 Answers

Implement a method/class that hides the list.

class YourClass {
    // intentionally incomplete
    private List<Type> listOfTypesOfGlasses;
    public void AddToList<T>() : where T: IGlass
    {
        listOfTypesOfGlasses.Add(typeof(T));
    }
}

Edit: below is the original answer here assuming that Type meant a placeholder, not System.Type.

All you should need to do is List<IGlass>.

or

You should write your own wrapper class around List<T> that has the constraint.

or

Subclass List<T> and put the generic constraint on it - however this practice is discouraged.

like image 98
Daniel A. White Avatar answered Nov 09 '25 03:11

Daniel A. White