.NET Using generic type parameters as constraints for other type parameters

By Indranil Chatterjee

We all know that generic type parameters can be constrained. They can also be used as constraints for other type parameters of the same generic type. This example illustrates one such scenario.

Let’s say we have a generic class Container<T>. We want to provide a generic Add<U> method which takes another instance of the class Container<U>, but the point is we cannot allow any type to be passed for U, since our container plays host to items of type T. At the same time, we need to allow types derived from T to be allowed. So we need to constrain U so that it is either same as T or derived from T. We can use T as a constraint for U to achieve that as shown below:

public class Container<T>
{
public void Add<U>(Container<U> items) where U : T
{
//Code
}
}

.NET Using generic type parameters as constraints for other type parameters  (1189 Views)