Derived classes cannot raise base class events

rbulph

Junior Contributor
Joined
Feb 17, 2003
Messages
397
I've just seen the above error message for the first time. Why can't they? Is there some logical reason for this?
 
There is a simple solution for this as seen in Windows Forms.
Put this in the base class:
C#:
protected virtual void On*EVENTHANDLER*(*EVENTARGS e)
{
    if (*EVENTHANDLER* != null)
    {
         *EVENTHANDLER*(this, e);
    }
}
As to why, I have absolutely no idea.
 
An overridden method can be sealed and an inherited field can be made private and protected with an accessor property. When dealing with events the only way to give the base class the ability to control an inheritor's use of an event is by disallowing the inheritor from directly invoking the event, leaving it up to the base class to explicitly provide a means of raising an event should it be necessary.

That might not necessarily be Microsoft's reason, however. There is also a technical limitation. At the MSIL level, an event is actually composed of four parts:
  • A private field whose type is a multi-cast delegate, for example System.EventHandler--this is where all the attatched event handlers are stored
  • A method to add a delegate to the private field
  • A method to remove a delegate from the private field
  • A piece of MSIL metadata that declares an event by providing a name, a method through which a delegate can be attatched (#2), and a method through which a delegate can be removed (#3).

Note that because the backing field (#1) is private, only the declaring class has access to it, not inheriting classes, therefore only the declaring class can invoke it.

Now, Microsoft could add a protected, read-only property that allows inheriting classes to obtain and invoke the underlying delegate, but why go out of your way to permit programming practices that break the OOP paradigm?
 
Back
Top