General type restriction

I struggle with some generics. Below is my setup:

interface I<T> { } [...] void Add<T>(T obj) where T : I<??> { } 

How can I guarantee that T in the Add method implements I ?

+4
source share
2 answers

The following signature allows Add to take any T that implements I<> with any type parameters.

 void Add<T,S>(T obj) where T : I<S> { } 

The disadvantage of using this method signature is that type inference does not work, and you need to specify all type parameters that look completely stupid:

 blah.Add<I<int>, int>(iInstance); 

A simpler approach is to use a signature:

 void Add<T>(I<T> obj) { } 
+8
source

You also need to pass parameter T.

 void Add<TI, TAny>(TI obj) where TI : I<TAny> 
+1
source

All Articles