Generic method with multiple constraints

C#Generics.Net 3.5

C# Problem Overview


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

C# Solutions


Solution 1 - C#

It is possible to do this, you've just got the syntax slightly wrong. You need a [where][1] for each constraint rather than separating them with a comma:

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

[1]: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint "Microsoft Docs | where constraint"

Solution 2 - C#

In addition to the main answer by @LukeH with another usage, we can use multiple interfaces instead of class. (One class and n count interfaces) like 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

Solution 3 - C#

In addition to the main answer by @LukeH, I have issue with dependency injection, and it took me some time to fix this. It is worth to share, for those who face the same issue:

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

It is solved this way. in containers/services the key is typeof and the comma (,)

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

This was mentioned in this answer.

Solution 4 - C#

Each constraint need to be on own line and if there are more of them for single generic parameter then they need to separated by comma.

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

Edited as per comment

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMartinView Question on Stackoverflow
Solution 1 - C#LukeHView Answer on Stackoverflow
Solution 2 - C#Hamit YILDIRIMView Answer on Stackoverflow
Solution 3 - C#Maytham FahmiView Answer on Stackoverflow
Solution 4 - C#mybraveView Answer on Stackoverflow