Janitha Tennakoon
Janitha Tennakoon

Reputation: 906

C# generics with same class and same class list

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>>

Upvotes: 0

Views: 1231

Answers (2)

Kit
Kit

Reputation: 21709

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> 

Upvotes: 4

Ruben
Ruben

Reputation: 6427

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()

Upvotes: 0

Related Questions