Generic interface type assignment

85 Views Asked by At

I would like to have some validators for input for different objects. On of these is User object. I want to have a generic interface validator for each child class which validates a specific object. The basevalidator is just an abstract class which contains the the abstract method "validate" and some other useful protected methods. But when i try to assign a new UserValidator to a Validator type i get an error. How could i rewrite this?

public interface Validator<T> {...}
public abstract class BaseValidator<T> : Validator<T> {...}
public class UserValidator : BaseValidator<User> {...

Validator v = new UserValidator(); //ERROR
1

There are 1 best solutions below

2
Mong Zhu On

Actually the error message:

Using the generic type 'Validator<T>' requires 1 type arguments

tells you what to do. You have to specify the generic parameter of the interface:

Validator<User> v = new UserValidator(); //NO ERROR

Much more important is where you want to use v. Because this determines whether User is known at compile time or not. Please post more context code, so I can adjust my answer to your actual situation