Search code examples
c#genericsinheritancecovariancecontravariance

The type cannot be used as type parameter 'T' in the generic type or method 'BaseController<T>'. There is no implicit reference


I'm trying to create a generic to simplify my codes (it's a web api project), but at somehow it's ended up becoming more complicated than I expected. What I'm trying to implement is something like this:

My First Idea

To simplify my whole real code, this is what I've written:

public interface IDatabaseTable { }

public class ReceiptIndex: IDatabaseTable { }

public interface IBackend<T> where T: IDatabaseTable { }

public class Receipts : IBackend<ReceiptIndex> { }

public class Generic<T> : SyncTwoWayXI, IBackend<T> where T:IDatabaseTable { }

public class BaseController<T> : ApiController where T: IBackend<IDatabaseTable>, new () { }

All of the line above created separately in its own file.

When I try to create controller that Inherit from BaseController

public class ReceiptsBaseController : BaseController<Receipts>

I get an error said

The type 'Receipts' cannot be used as type parameter 'T' in the generic type or method 'BaseController'. There is no implicit reference conversion from 'Receipts' to 'IBackend'.

I try to find a similar problem and end up with something called Covariance and Contravariance problem. Can anyone give feedback for what I'm trying to do or maybe something that can I do to simplify it.


Solution

  • You can try to specify the T in IBackend. Like this:

    public class BaseController<T, TBackEndSubType> : ApiController
        where T : IBackend<TBackEndSubType>, new()
        where TBackEndSubType : IDatabaseTable { }
    
    public class ReceiptsBaseController : BaseController<Receipts, ReceiptIndex> { }