I have a generic method which has two generic parameters. I tried to compile the code below but it doesn't work. Is it a .NET limitation? Is it possible to have multiple constraints for different parameter?
public TResponse Call<TResponse, TRequest>(TRequest request) where TRequest : MyClass, TResponse : MyOtherClass
Multiple interface constraints can be specified. The constraining interface can also be generic. In a nullable context in C# 8.0 and later, T must be a non-nullable type that implements the specified interface.
A Generic class can have muliple type parameters.
Interface Type Constraint You can constrain the generic type by interface, thereby allowing only classes that implement that interface or classes that inherit from classes that implement the interface as the type parameter.
It is possible to do this, you've just got the syntax slightly wrong. You need a where
for each constraint rather than separating them with a comma:
public TResponse Call<TResponse, TRequest>(TRequest request) where TRequest : MyClass where TResponse : MyOtherClass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With