I have a class called Ship and a class called Lifeboat
Lifeboat inherits from Ship.
Ship contains a method called Validate() which is called before save and it has an abstract method called FurtherValidate() which it calls from Validate. The reason this is in place is so when you call validate on the base it also validates the class that is inheriting. So we have
public class Ship public bool Validate() { //validate properties only found on a ship FurtherValidate(); } public abstract bool FurtherValidate();
So Lifeboat has
public override bool FurtherValidate() { //validate properties only found on a lifeboat }
This means anyone implementing Ship also needs to provide their own validation for their class and it’s guaranteed to be called on the save as the base ship. Validate() is called which in turns calls the inherited validate.
How can we re work this so we still force inherited classes to implement FurtherValidate() but FurtherValidate() can never be called by the programmer. Currently you can called Lifeboat.FurtherValidate() and I want to somehow prevent this.
The exact scenario you describe isn’t possible. You can restrict access to the
FurtherValidatemethod to only derived classes by using theprotectedaccess modifier. You could also restrict it to only classes in the same assembly by using theinternalmodifier, but this would still allow the programmer writing the derived class to call FurtherValidate any time they wish. Using both protected and internal combines the two and really means that is restricted to derived classes or classes defined in the same assembly.Using the [EditorBrowsable] attribute is an IDE trick that will hide the method from IntelliSense (unless the other programmer has turned on the right options in VS). That will effectively prevent most people from calling it (if they can’t see it, it doesn’t exist).
You could possibly achieve this using reflection to interrogate who your caller is, but I think the performance costs of doing this would be too high compared to the benefit.