0

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?

0

2 Answers 2

4

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>
{

}
Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

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.