Reputation: 22814
Let's say I have some generic interface IMyInterface<TParameter1, TParameter2>
.
Now, if I'm writing another class, generic on it's parameter T
:
CustomClass<T> where T : IMyInterface
how should this be done?
(current code won't compile, because IMyInterface
is dependent on TParameter, TParameter2
).
I assume it should be done like:
CustomClass<T, TParameter1, TParameter2> where T: IMyInterface<TParameter1,
TParameter2>
but I might be wrong, could you advice me please?
Upvotes: 0
Views: 2325
Reputation: 57919
Do you really want to use it as a constraint (with the 'where' keyword)? Here are some examples of straight implementation:
interface ITwoTypes<T1, T2>
class TwoTypes<T1, T2> : ITwoTypes<T1, T2>
Or, if you know the type(s) your class will use, you don't need a type parameter on the class:
class StringAndIntClass : ITwoTypes<int, string>
class StringAndSomething<T> : ITwoTypes<string, T>
If you are using the interface as a constraint and don't know the types to specify explicitly, then yes, you need to add the type parameters to the class declaration, as you supposed.
class SomethingAndSomethingElse<T, TSomething, TSomethingElse> where T : ITwoTypes<TSomething, TSomethingElse>
class StringAndSomething<T, TSomething> where T : ITwoTypes<string, TSomething>
Upvotes: 0
Reputation: 1038720
It's exactly as you have it, you need to specify the TParameter1
and TParameter2
generic arguments in a class which requires a generic constraint on IMyInterface
:
public interface IMyInterface<TParameter1, TParameter2>
{
}
public class CustomClass<T, TParameter1, TParameter2>
where T : IMyInterface<TParameter1, TParameter2>
{
}
or you could have them fixed:
public class CustomClass<T>
where T : IMyInterface<string, int>
{
}
Upvotes: 4