This rule is Obsolete | |
Synopsis: | Raise events through a protected virtual method |
Language: | C# |
Severity Level: | 9 |
Category: | Delegates and events |
Description: |
If a derived class wants to intercept an event, it can override such a virtual method, do its own work, and then decide whether or not to call the base class version (whether or not this should be done, is mentioned by the base class documentation). Since the derived class may decide not to call the base class method, ensure that it does not do any work required for the base class to function properly. Name this method
///<summary>An example class</summary> public class Connection { // Event definition public event EventHandler Closed; // Method that causes the event to occur public void Close() { // Do something and then raise the event OnClosed(EventArgs.Empty); } // Method that raises the Closed event. protected virtual OnClosed(EventArgs args) { if (Closed != null) { Closed(this, args); } } } ///<summary>Main entrypoint.</summary> public static void Main() { Connection connection = new Connection(); connection.Closed += new EventHandler(OnClosed); // For .NET 2 // connection.Closed += OnClosed; } ///<summary>Event handler for the Closed event</summary> private static void OnClosed(object sender, EventArgs args) { ... } |