Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method with multiple constraints

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 
like image 914
Martin Avatar asked Feb 26 '09 00:02

Martin


People also ask

Can generic class have multiple constraints?

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.

Can a generic class have multiple parameters?

A Generic class can have muliple type parameters.

What does the generic constraint of type interface do?

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.


1 Answers

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 
like image 162
LukeH Avatar answered Oct 10 '22 18:10

LukeH