Here\'s the code:
public interface IValidator
{
bool IsValid(T obj);
}
public class OrderValidator: IValidator
{
// ...
}
public
The cast doesn't work because IValidator
and IValidator
are totally unrelated types. IValidator
is not a subtype of IValidator
, so they can't be cast.
C# does support multiple interface inheritance, so the simplest way to handle this is to make your order validator inherit from an interface for both validator types, that way it you will be able to cast it to either interface as required. Obviously this means you will have to implement both interfaces and specify how to handle the base when a BaseEntity
provided doesn't match the type the validator is for.
Something like this:
public class OrderValidator : IValidator, IValidator
{
public bool IsValid(Order obj)
{
// do validation
// ...
return true;
}
public bool IsValid(BaseEntity obj)
{
Order orderToValidate = obj as Order;
if (orderToValidate != null)
{
return IsValid(orderToValidate);
}
else
{
// Eiter do this:
throw new InvalidOperationException("This is an order validator so you can't validate objects that aren't orders");
// Or this:
return false;
// Depending on what it is you are trying to achive.
}
}
}
This relates to what Heinzi says about not being able to cast because an IValidator
needs to be able to validate BaseEntities
, which your current OrderValidator
can't do. By adding this multiple interface you explicitly define the behaviour for validating BaseEntities
(by either explicitly ignoring it or causing an exception) so the cast becomes possible.