Coder Perfect

Multiple limitations on a generic method

Problem

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

Asked by Martin

Solution #1

It is feasible to do so; you simply have the syntax incorrect. Instead of using a comma to separate the constraints, you’ll need a where clause:

public TResponse Call<TResponse, TRequest>(TRequest request)
    where TRequest : MyClass
    where TResponse : MyOtherClass

Answered by LukeH

Solution #2

We can utilize many interfaces instead of classes, in addition to @LukeH’s primary response with another usage. (One class and n number of interfaces) similar to this

public TResponse Call<TResponse, TRequest>(TRequest request)
  where TRequest : MyClass, IMyOtherClass, IMyAnotherClass

or

public TResponse Call<TResponse, TRequest>(TRequest request)
  where TRequest : IMyClass,IMyOtherClass

Answered by Hamit YILDIRIM

Solution #3

In addition to @LukeH’s primary response, I have a dependency injection issue that took me some time to resolve. It’s worth sharing for people who are dealing with the same problem:

public interface IBaseSupervisor<TEntity, TViewModel> 
    where TEntity : class
    where TViewModel : class

This is how it is resolved. Containers and services typeof is the key, and the comma is the separator (,)

services.AddScoped(typeof(IBaseSupervisor<,>), typeof(BaseSupervisor<,>));

This was mentioned in the previous response.

Answered by Maytham

Solution #4

Each restriction should be on its own line, with commas between them if there are more than one for a single generic parameter.

public TResponse Call<TResponse, TRequest>(TRequest request)
    where TRequest : MyClass 
    where TResponse : MyOtherClass, IOtherClass

Edited in accordance with commen

Answered by mybrave

Post is based on https://stackoverflow.com/questions/588643/generic-method-with-multiple-constraints