Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic in type constraint

I'm struggling with some generics. The following is my setup:

interface I<T> { }

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

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

like image 415
Jon List Avatar asked Jan 21 '23 14:01

Jon List


1 Answers

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

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

The downside of using this method signature is that type inference doesn't kick in and you have to specify all the type parameters, which looks downright silly:

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

A much simpler approach is to use the below signature:

void Add<T>(I<T> obj) {
}
like image 181
Igor Zevaka Avatar answered Jan 31 '23 21:01

Igor Zevaka