Often, in C# documentation, you come across a member where the description says something along the lines of “be sure to call the base method if you override this.”
Is there a way to ensure at compile time that one has actually called the base function?
Here’s an example:
Implementing a Dispose Method
From the first lines:
A type’s Dispose method should release
all the resources that it owns. It
should also release all resources
owned by its base types by calling its
parent type’s Dispose method.
EDIT
I was browsing, and I came across this article, which seems rather relevant. It’s more of a small than an error, ie. it has valid uses (such as those mentioned):
You can’t enforce it, but you can do it via a call like
base.Foo(bar).baseallows you to access members of the class you’re inheriting from.You can kind of enforce this behavior by using the template method pattern. For example, imagine you had this code:
The trouble here is that any class inheriting from
Animalneeds to callbase.Speak();to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:In this case, clients still only see the polymorphic
Speakmethod, but theAnimal.Speakbehavior is guaranteed to execute. The problem is that if you have further inheritence (e.g.class Dachsund : Dog), you have to create yet another abstract method if you wantDog.Speakto be guaranteed to execute.