0

I have defined a generic class where T can be a specific interface or a collection of the interface.

public  class BaseResponse<T> where T :  IBaseResource, ICollection<T>, new()

However, when I try to create BaseResponse using IBaseResource I get the following error.

'System.Collections.Generic.List' cannot be used as type parameter 'T' in the generic type or method 'BaseResponse'. There is no implicit reference conversion from 'System.Collections.Generic.List<.Resources.IBaseResource >' to 'Vehicle.Api.Resources.IBaseResource'.

I even tried with following as well.

public  class BaseResponse<T> where T :  IBaseResource, ICollection<IBaseResource>, new()

Is the way I am defining multiple constraints is wrong or can't I use the ICollection of the same interface when defining multiple constraints? If it is achievable how can I achieve this?

edit - To further clarify what I am expecting to achieve, I am implementing a rest API where the response will be given by BaseResponse. For example, GET with single method will include BaseResponse<Entity> and GET will include BaseResponse<List<Entity>>

3
  • 2
    No constraints dont work like this, there is no OR constraint. also using T where T is a collection of T, doesnt make sense Commented May 2, 2019 at 3:44
  • Youll have to have a less restrictive constraint and figure it out at runtime, or reconsider your design Commented May 2, 2019 at 3:50
  • This sounds like an XY Problem. Commented May 2, 2019 at 3:52

2 Answers 2

4

As mentioned in the comments, constraints are ANDed not ORed.

Without knowing what the purpose of your implementation is or what it looks like, it's difficult to address this question.

Perhaps you can parameterize your generic on two types:

public  class BaseResponse<T, U> 
     where T : IBaseResource, new()
     where U : ICollection<T> 
Sign up to request clarification or add additional context in comments.

Comments

0

It is a bit unclear what you want to do, but in your first attempt you specify that T must implement IBaseResource and that the collection should implement IBaseResource as well. I assume that is not what you want. That is also what the error message shows. It shows that List<T> does not implement IBaseResource

Does this solve your problem?

public  class BaseResponse<ICollection<T>> where T :  IBaseResource, new()

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.