I saw some tutorials and I couldn't understand why would they suggest to raise an event from Virtual Protected method, instead of directly, what is the difference?
public delegate void SomethingEventHandler(string s);
public event SomethingEventHandler Something;
public void Main() {
// Raising an event
OnSomething(); // Via method
Something("something"); // Directly
}
protected virtual void OnSomething()
{
Something("something");
}
See "Design Guidelines for Developing Class Libraries", Event Design:
Do use a protected virtual method to raise each event. This is applicable only to non-static events on unsealed classes, not to structures, sealed classes, or static events.
Complying with this guideline allows derived classes to handle a base class event by overriding the protected method. The name of the protected virtual (Overridable in Visual Basic) method should be the same as the event name prefixed with
On
. For example, the protected virtual method for an event named"TimeChanged"
is named"OnTimeChanged"
.⚠ Important
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
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