Overriding / hiding the embedded interface

I am having trouble redefining a method that explicitly implements the interface.

I have two classes. The base, called OurViewModel , and the inherited, called MyViewModel . They share a method called Validate , and until recently, I managed to hide the base version of the method, for example:

 public class OurViewModel { public bool Validate(ModelStateDictionary modelState){ return true; } } public class MyViewModel : OurViewModel { public new bool Validate(ModelStateDictionary modelState) {return false;} } 

All this changed a couple of days ago. A new interface appeared on the scene -

 public interface IValidatableObject { IEnumerable<ValidationResult> Validate(ValidationContext validationContext); } 

Subsequently, OurViewModel was also changed. I did not ask for this, but it happened, and I have to live with him. The class now looks like this:

 public class OurViewModel : IValidatableObject { IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) {..} } 

I find it difficult to determine how to override or hide this rewritten Validate method in MyViewModel. If I try to put the keyword new method signatures (as before), I get a compilation error. I also cannot declare the Validate method as virtual in OurViewModel, as it explicitly implements the interface.

What to do? If I just reimplement Validate in MyViewModel using the signature from the IValidatableObject document, will this hide the implementation in OurViewModel, or am I asking for any problems due to inheritance rules?

+2
source share
2 answers

I think you need to implement this interface implicitly and in a derived class.

 public class MyViewModel : OurViewModel, IValidatableObject { IEnumerable<ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { //... } } 

And then

 OurViewModel v = new OurViewModel(); MyViewModel m = new MyViewModel(); IValidatableObject ivo = v; ivo.Validate(null); ivo = m; ivo.Validate(null); 

In addition, if the interface is explicitly implemented, you can only access the implementation through a link to the interface. Remember, if you try to do

 OurViewModel v = new OurViewModel(); v.Validate(null); 

It will call the original Validate method of the class, not the interface implementation. I think that old methods should be removed to avoid possible errors.

+4
source

Do you really need to explicitly implement IValidatableObject in the base class?

The solution will be: implement IValidatableObject implicitly in the base class, mark it as virtual.

: -

Then we implement IValidatableObject in the derived class, implicitly and mark it as virtual new. Remember to use the interface name in the derived class definition.

This is a slightly different approach, which is arranged for the answer of Konstantin Vasiltsov. Using this approach, you can have more derived MyViewModel classes that can override behavior.

0
source

All Articles