In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:
public class A { public event EventHandler SomeEvent; public void someMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); } } public class B : A { public void someOtherMethod() { if(SomeEvent != null) SomeEvent(this, someArgs); // << why is this not possible? //Error: The event 'SomeEvent' can only appear on the left hand side of += or -= //(except when used from within the type 'A') } }
Why isn’t it possible?
And what is the common solution for this kind of situation?
The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.
For an explanation of the why read Jon Skeet’s answer or the C# specification which describes how the compiler automatically creates a private field.
Here is one possible work around.
Edit: Updated code based upon Framework Design Guidelines section 5.4 and reminders by others.