2

I have a generic interface and I want to constrain types that this generic parameter can accept. Here is the interface:

public interface IBaseRequestRepository<T> where T : IRequestPackage, IRequestDynamicPackage, IRequestHotelOnly, IRequestFlightOnly { IList GetByOccupancyAndTravelDate(int occupancyId, int travelBegYear, int travelBegDate, int travelEndYear, int travelEndDate); } 

But this gives an error:

Error 1 The type 'IRequestPackage' cannot be used as type parameter 'T' in the generic type or method 'IBaseRequestRepository'. There is no implicit reference conversion from 'IRequestPackage' to 'IRequestFlightOnly'.

Any suggestions?

5 Answers 5

4

You need to satisfy all generic constraints and not just one.

Thus you can't substitute IRequestPackage into T because it doesn't derive from all the other interfaces.

You can pass in either an interface type that inherits from all the interfaces you specified as a constraint or a class type that implements all these interfaces.

Sign up to request clarification or add additional context in comments.

Comments

3

The error message suggests that IRequestPackage does not inherit from IRequestFlightOnly - does it?

Note that the where clause is an AND relationship, not an OR - so your where clause is that T must implement ALL of

  • IRequestPackage,
  • IRequestDynamicPackage
  • IRequestHotelOnly,
  • and IRequestFlightOnly

Comments

2

Looks like you want an IRequest interface or RequestBase abstract class ;)

Comments

0

You should use a type that implement all the interfaces specified by the constraint, not just one of them. It's an "AND", not an "OR"...

Comments

0

You should reconsider your type constraints and your program structure. It looks like you are missing a base interface or an abstract base class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.