Let's say I have this method in my base class.
public virtual void Close ()
{
if (!IsOpen) return;
Dispose();
RaiseClosed();
}
I want child class to freely modify the method, but make sure it calls Dispose()
first, then later it calls RaiseClosed()
. They can do anything in before, after, or in between the two.
How can I enforce child classes to call Dispose()
and RaiseClosed()
at some point?
EDIT: I guess I didn't clarify the question well. Derived methods may do something before/after Dispose()
, and before/after RaiseClosed()
. So it's not sufficient to make sure it calls Dispose()
and RaiseClosed()
in an order because the derived methods may do something in between, or even after RaiseClosed()
.
One way is to simply not make Close
a virtual
method. Instead have another method which is specifically designed to be overriden and call that from your Close
method which itself properly enforces the variants you want
public void Close() {
if (!IsOpen) return;
try {
CloseCore();
}
finally {
Dispose();
RaiseClosed();
}
}
protected virtual void CloseCore()
{
// Derived types override this to customize their close
// behavior
}
First declare the method as not virtual in the following way:
public void Close ()
{
if (!IsOpen) return;
DoClosingStuff();
Dispose();
RaiseClosed();
}
and then make virtual the method DoClosingStuff()
public virtual void DoClosingStuff()
{
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With