umbersar
umbersar

Reputation: 1931

constraining a generic type at absract class level or interface level

I want to restrict a generic type to be of particular type. In this case, i want the generic type T to be of something that is IComparable. And i want the restriction to happen at parent class level(or parent interface level). Here is sample code:

abstract class BaseContainer<T> where T : IComparable<T> {
    protected List<T> container;
}

class QueueCustom<T> : BaseContainer<T>  {
    public QueueCustom() {
        this.container = new List<T>();
    }
}

This throws a error:

The type 'T' cannot be used as type parameter 'T' in the generic type or method 'BaseContainer'. There is no boxing conversion or type parameter conversion from 'T' to 'System.IComparable'.

I can restrict the type T at the child class level though:

abstract class BaseContainer<T> {
    protected List<T> container;
}

class QueueCustom<T> : BaseContainer<T> where T : IComparable<T>   {
    public QueueCustom() {
        this.container = new List<T>();
    }
}

How do i go about doing it at parent class and not at the derived class?

Upvotes: 0

Views: 26

Answers (1)

Administrator
Administrator

Reputation: 327

You can do it in both.

By using class QueueCustom : BaseContainer, You declare a statement saying "The type chosen for derived class will be base class's type as well".

This means that, in order to match base class's requirements, you have to demand them as well.

Upvotes: 0

Related Questions