Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the different between raising an event from Protected Virtual Void method or directly?

Tags:

c#

events

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");
}
like image 852
J. Doe Avatar asked Dec 04 '22 01:12

J. Doe


1 Answers

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.

like image 169
AlexD Avatar answered Dec 08 '22 01:12

AlexD