Flaviu
Flaviu

Reputation: 49

Generic interface type assignment

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

Upvotes: 1

Views: 83

Answers (1)

Mong Zhu
Mong Zhu

Reputation: 23732

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

Upvotes: 2

Related Questions