Here\'s the code:
public interface IValidator
{
bool IsValid(T obj);
}
public class OrderValidator: IValidator
{
// ...
}
public
Maybe it helps you if I explain why this cast is forbidden: Assume that you have the following function
void myFunc(IValidator myValidator) {
myValidator.IsValid(new BaseEntity());
}
This code would compile correctly. Nevertheless, if you passed an OrderValidator
to this function, you would get a run-time exception, because OrderValidator.IsValid
expects an Order, not a BaseEntity. Type safety would no longer be maintained if your cast were allowed.
EDIT: C# 4 allows for generic co- and contravariance, but this would not help in your case, since you use T as an input parameter. Thus, only casting to an IValidator
could be done in a type-safe way.
So, to be clear, you cannot cast OrderValidator
to IValidator
because your OrderValidator can only validate orders, not all kinds of BaseEntities. This, however, is what would be expected of an IValidator
.