I have base class(CompareAttribute) which implemented IClientValidatable
[AttributeUsage(AttributeTargets.Property)]
public class NotContainsAttribute : CompareAttribute
{
}
I want to override method IEnumerable<ModelClientValidationRule> GetClientValidationRules
but i can’t do that because it is not virtual(cannot override inherited member, because it is not marked virtual, abstract, or override).
So i just declare my own method in my NotContainsAttribute class
public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
}
After i run the program all working like expected but i get warning in compile time that my class hides inherited member, (Warning "NotContainsAttribute" hides inherited member Use the new keyword if hiding was intended.)
But if I use new keyword
public new IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
yield return new ModelClientValidationNotContains (this.FormatErrorMessage(metadata.GetDisplayName()), CompareAttribute.FormatPropertyForClientValidation(this.OtherProperty));
yield break;
}
In such case my method not used, base class method used instead.
I want my method to be used, without new keyword i get it used but why compiler saying that i need to use new keyword if hiding was intended?
I understand that if hiding was intended means that if you want to hide base method and use your method insteard mark it with new keyword but on practice it is really hiding my method.
May be some one may clarify that and is it good practice to declare method with the same name if that method in base class not allowed to be overridden but really you need to override it?
I don’t think your assessment of the situation is correct: If the base class method is not marked as virtual then your method implementation will be hiding it by default.
From MSDN:
You just get a compiler warning because often this is not what the intention of the programmer is and it gives you a chance to correct this common mistake – usually you want to override a base class implementation. It should not make a difference whether or not you mark your method with new – this just makes it explicit that you are in fact hiding the base class method.
Also note that hiding a base class method will not allow this method to be used in a polymorphic fashion: object references typed as the base class that point to an instance of your derived class will use the base class method instead:
So your method only will be called if you call the method on an object reference with type
NotContainsAttribute:Also see “Versioning with the Override and New Keywords (C# Programming Guide)” and “Polymorphism, Method Hiding and Overriding in C#” as a reference.