Reputation:
If I want a generic method to have many generic types, e.g. up to 16.
Do I have to overload the method 16 times or is there any smarter way to do this?
public interface IMyInterface { }
public class MyClass {
public void MyMethod<T1>() where T1 : IMyInterface { }
public void MyMethod<T1, T2>() where T1 : IMyInterface where T2 : IMyInterface { }
public void MyMethod<T1, T2, T3>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface { }
public void MyMethod<T1, T2, T3, T4>() where T1 : IMyInterface where T2 : IMyInterface
where T3 : IMyInterface where T4 : IMyInterface { }
// All the way to T16...
// Is there any smarter way of doing this
// instead of having to write it 16 times?
}
Upvotes: 4
Views: 405
Reputation: 23732
if you look at the documentation of Action<T1, T2, ....>
it seems that you need to implement all overloads singlehandedly.
Here is the reference source of it. As you see it is done as in your example.
A more detailed answer as to why a params
equivalent does not exist can be found by Jon Skeet here.
It states:
"Fundamentally Func<T>
and Func<T1, T2>
are entirely unrelated types as far as the CLR is concerned, and there's nothing like params to specify multiple type arguments."
Upvotes: 3