4

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?

1
  • Sorry - Add is NOT part of the interface I but a method on a different class Commented Aug 15, 2010 at 13:17

2 Answers 2

8

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) {
}
Sign up to request clarification or add additional context in comments.

1 Comment

void Add<T>(I<T> obj) did it. Thanks!
1

You need to pass the T parameter to add also.

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

1 Comment

TI is a generic parameter, not a generic itself, so you can't do TI<TAny>. Shouldn't your parameter just be TI? And your constraint should be where T : I<TAny>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.