C# Query Object Pattern: Have query return IEnumerable or single result on generic interface

548 Views Asked by At

I have an interface which runs a query based on the query parameter and the query result

public interface IQueryParam {}
public interface IQueryResult {}

public interface IQuery<in TQueryParam, out TResult>
  where TQueryParam : IQueryParam
  where TResult : IQueryResult
{
    TResult RunQuery(TQueryParam query);
}

public class GetBushCodes : IQuery<GetalBushCodesParam, ReturnBushCode[]>
{
  ReturnBushCode[] RunQuery(GetalBushCodesParam param) { /*TODO*/ }
}

I want any class that inherits from IQuery have the ability to return a single instance of IQueryResult or an IEnumerable or Array of IQueryResult. My current setup won't allow it and the compiler yells at me for GetBushCodes:

The type 'System.Collections.Generic.IEnumerable<App.Domain.Queries.ReturnBushCode>' 
cannot be used as type parameter 'TResult' in the generic type or 
method 'App.Domain.Queries.IQuery<TQueryParam,TResult>'. There is no implicit 
reference conversion from 
'System.Collections.Generic.IEnumerable<App.Domain.Queries.ReturnBushCode>' to 
'App.Domain.Queries.IQueryResult'.

I do not want to use the setup IQueryParam<TResult> where TResult : IQueryResult because that seems to restrictive and I want to try to keep the IQueryResult constraint on the IQuery because GetBushCodes compiles if I get rid of the constraint.

0

There are 0 best solutions below