Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic interface in C#

Tags:

c#

generics

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?

like image 408
user593791 Avatar asked Jan 29 '26 16:01

user593791


1 Answers

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.

like image 94
CodesInChaos Avatar answered Jan 31 '26 04:01

CodesInChaos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!