Connor Bishop Connor Bishop - 5 months ago 14
ASP.NET (C#) Question

C# class constraints with Generic Type arguments

I have this generic class with a condition on the generic type:

public abstract class ReportModel<ReportHandler> where ReportHandler : IReportHandler

Then I have this Controller class

public abstract class ReportController<ReportModelType> : Controller

What I need is a condition that ReportModelType must inherit the abstract ReportModel class. The trouble is that Im then forced to give a type argument for ReportModel, I dont want to specify an argument. I need some kind of wildcard like this:

public abstract class ReportController<ReportModelType> : Controller where ReportModelType : ReportModel<*any type which satifies ReportModels contraint>

Can anyone offer a solution?

Answer Source

As far as I know, there isn't a generic wildcard in C#, so all you can do is to find an alternative.

I suggest that you add another generic type parameter ReportHandler to ReportController, constraint the new type parameter to implement IReportHandler and make ReportModelType implement ReportModel<ReportHandler>.

public abstract class ReportController<ReportModelType, ReportHandler> : Controller
    where ReportHandler : IReportHandler
    where ReportModelType: ReportModel<ReportHandler>