Abstract/Virtual Members to Provide Common & Derived Combined Functionality - C#
-
26-09-2019 - |
Question
I've done this before - just can't remember the trick.
If i have an abstract class:
public abstract class Post
And a set of deriving classes:
public class Photo : Post
I want to force the deriving classes to implement a method called Validate(), but at the same time providing core validation at the Post level.
I can create a method: public abstract void Validate() in Post, which would force the deriving classes to implement the method, but then how do i perform the Post (base) validation?
The end result is i want to be able to do this:
public class BLL
{
public void AddPost(Post post)
{
post.Validate(); // includes "Post" validation, any deriving validation.
repository.Add(post);
}
}
How can i do it?
Solution
Here is what you want:
public abstract class Post {
// Default validation technique
public void Validate()
{
// your base validation
// Then call the specific validation technique
ExtraValidate();
}
// Forces subclasses to provide validation technique
protected abstract void ExtraValidate();
}
This will force base classes to implement a validation technique, and the base Validate will get called by external users.
It is impossible to make a method abstract, and provide a default implementation.
OTHER TIPS
Create a public template method in the base class and have it call the derived class validation method:
public abstract class Post {
public void Validate() {
// Post validation
ValidateDerived();
}
protected abstract void ValidateDerived();
}
This forces derived classes to implement the method, but provides common validation logic for the Post class. Note that Validate() is not virtual itself. This is safer than forcing derived classes to have to remember to call base.Validate().