Written July 11, 2007 at 07:29 MDT Tagged .net 2.0, .net 3.0 and c sharp
If you are now coding in .Net 2.0/3.0/3.5 and are creating types that expose events. Chances are you have started leveraging the EventHandler
In .Net 2.0/3.0/3.5 these steps can now become:
This can actually become slightly better. Instead of always creating a class that derives from EventArgs if you need to pass custom data; create a parameter object that encapsulates the information you would want to propagate in the event. This class does not need to inherit from EventArgs. Then create the following utility class:
public class EventArgs<T> : EventArgs
{
private T eventData;
public EventArgs(T eventData)
{
this.eventData = eventData;
}
public T EventData
{
get { return eventData; }
}
}
This means that the 3 steps above can now be changed to:
So if I had a parameter object that looked like this:
public class ReportingPeriod
{
private DateTime start;
private DateTime end;
public DateTime Start
{
get { return start; }
}
public ReportingPeriod(DateTime start, DateTime end)
{
this.start = start;
this.end = end;
}
}
I would be able to create a type that raises an event to propagate this data as follows (using implicit registration):
public class ReportTrigger
{
public event EventHandler<EventArgs<ReportingPeriod>> RunReport;
}
Or using explicit registration:
public class ReportTrigger
{
private EventHandler<EventArgs<ReportingPeriod>> subscribers;
public event EventHandler<EventArgs<ReportingPeriod>> RunReport
{
add
{
subscribers += value;
}
remove
{
subscribers -= value;
}
}
}
Develop With Passion!