I have classes which implement interfaces of classes derived from a common base. Is there any way that I can combine these to work with them as a set?
I have been exploring co and contravariance but without success.
Thanks for your help.
void Main()
{
var textAnswers = new IAnswerValidator<TextQuestion, TextAnswer>[] { new NoDogsValidator(), new MaxLengthValidator() };
var dateAnswers = new IAnswerValidator<DateQuestion, DateAnswer>[] { new NotChristmasDayValidator() };
// Can I combine into a list or enumerable?
// var allValidators = new List<IAnswerValidator<QuestionBase, AnswerBase>>();
// allValidators.AddRange(textAnswers);
// allValidators.AddRange(dateAnswers);
// The goal is to be able to combine so as to be able to work on them as a set.
}
public class ValidationResult { }
public class AnswerBase { }
public class TextAnswer : AnswerBase { }
public class DateAnswer : AnswerBase { }
public class QuestionBase { }
public class TextQuestion : QuestionBase { }
public class DateQuestion : QuestionBase { }
public interface IAnswerValidator<TQuestion, TAnswer> where TQuestion : QuestionBase, new() where TAnswer : AnswerBase, new()
{
ValidationResult Validate(TQuestion question, TAnswer answer);
}
public class NoDogsValidator : IAnswerValidator<TextQuestion, TextAnswer>
{
public ValidationResult Validate(TextQuestion question, TextAnswer answer) { return new ValidationResult(); } // simplified
}
public class MaxLengthValidator : IAnswerValidator<TextQuestion, TextAnswer>
{
public ValidationResult Validate(TextQuestion question, TextAnswer answer) { return new ValidationResult(); } // simplified
}
public class NotChristmasDayValidator : IAnswerValidator<DateQuestion, DateAnswer>
{
public ValidationResult Validate(DateQuestion question, DateAnswer answer) { return new ValidationResult(); } // simplified
}