The EventArgs
class is necessary because if you wanted to extend your event to provide more information in the future, you would have portability problems for all clients using the original method signature of the original event.
For example,
public void IHandleEventVersion1(string p1, int p2)
{
....
}
Now you want to provide more information in event EventVersion1
above (you want to include a char
). You would then have to force the client rewrite their event handling to to match your new requirements like so:
public void IHandleEventVersion1(string p1, int p2, char p2)
{
...
}
See how awkward it could become when trying to provide more information?
So, the EventArgs
class provides a common design pattern to programme against, allowing you and me to quickly extend the data we want to provide for an event.
The general coding pattern of the eventing framework is such:
Basic event handling strategy
- Define an
event
that consumers of your class can subscribe to
- Define a
delegate
signature that the event declares (yes, you can also use the .NET 2.0 generic version of EventHandler
, namely, EventHandler<TEventArgs>
)
- Provide a
protected
virtual
method for inheritors to override in response to the event being raised in your base class
In the base class that declares your event, provide a base implementation of the protected
method where you actually raise the event.
public class MyClass
{
public event EventHandler /* (point 2) */ MyEvent; /* (point 1) */
// (point 3 + 4)
protected virtual void OnMyEvent()
{
EventHandler temp = MyEvent;
if (temp != null)
temp(this, EventArgs.Empty);
}
public void SomeMethodThatWillRaiseTheEvent()
{
....
OnMyEvent();
}
}