0

I have the following generic class:

public class DomainValidator<TRequest> : IValidator<TRequest> where TRequest : IRequest, IRequest<object>
{
}

As you can see, I have 2 types specified for type of TRequest: IRequest with no type, and IRequest<object> with a type of any.

If I use this DomainValidator class anywhere, Visual Studio compiler always complains that the type is not convertable to type IRequest, because it has it's own type parameter.

I have looked at other similar questions, but none of them have a type parameter, which has it's own type. Is it possible to do what I'm trying to achieve?

UPDATE

Here is how I am using this generic class and where it fails.

The following class RequestThatDoesntWorkValidator does not work, because RequestThatDoesntWork does not provide a type for IRequest as it doesn't need to:

public class RequestThatDoesntWorkValidator : DomainValidator<RequestThatDoesntWork>
{

}

public class RequestThatDoesntWork : IRequest
{

}

But the following class RequestThatDoesWorkValidator seems to work because RequestThatDoesWork provides a type for IRequest:

public class RequestThatDoesWorkValidator : DomainValidator<RequestThatDoesWork>
{

}

public class RequestThatDoesWork : IRequest<List<string>>
{

}

I hope this makes more sense.

ViqMontana
  • 5,090
  • 3
  • 19
  • 54
  • Can you please post a code snippet that shows us what exactly doesn't compile? It sounds like you are trying to cast a DomainValidator to an IRequest, which doesn't make any sense. – John Wu Jun 18 '18 at 18:28
  • @JohnWu please see my updated queston. – ViqMontana Jun 19 '18 at 08:19
  • 1
    When you say "I have 2 types specified for type of `TRequest`", do you want `TRequest` to implement *both* the listed interfaces, or *either* of the listed interfaces? Because what you've got at the moment requires `TRequest` to satisfay *both* the listed interfaces. In fact, you can't actually say 'require `TRequest` to implement `IRequest` *or* `IRequest<>`'. – AakashM Jun 19 '18 at 08:41
  • 1
    see also https://stackoverflow.com/a/1541173/71059 https://stackoverflow.com/questions/1891656/non-strict-multiple-interface-type-parameter-constraints – AakashM Jun 19 '18 at 08:44
  • @AakashM thank you, that's what I was looking for. I needed a base interface. – ViqMontana Jun 19 '18 at 14:53

1 Answers1

1

You need to add a type parameter to your own type to pass as that nested parameter:

public class DomainValidator<TRequest, TInner> : IValidator<TRequest> 
       where TRequest : IRequest, IRequest<TInner>
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964