The Basic Event Pattern
Creating an event is a simple process. Declare the event using the event
keyword and create a suitable method to raise it.
public class YourClass
{
public event EventHandler Xxx;
protected virtual void OnXxx(EventArgs e)
{
EventHandler eh = Xxx;
if (eh != null)
eh(this, e);
}
}
Passing Data
This is also simple. We just need to create a modified EventArgs
and EventHandler
.
Here we will pass an integer.
public class XxxEventArgs : EventArgs
{
private int value;
public XxxEventArgs(int value)
{
this.value = value;
}
public int Value
{
get { return value; }
}
}
public delegate void XxxEventHandler(object sender, XxxEventArgs e);
In Use:
public class YourClass
{
public event XxxEventHandler Xxx;
protected virtual void OnXxx(XxxEventArgs e)
{
XxxEventHandler eh = Xxx;
if (eh != null)
eh(this, e);
}
}
Passing More Complex Data
To return more complex information or multiple objects, simply create a suitable EventArgs
derived class and delegate.
In fact, you can avoid creating your own delegate by using the generic version of EventHandler
!
Here's an example:
public class GotDataEventArgs : EventArgs
{
private byte[] data;
private int id;
private string name;
private DateTime timeStamp;
public GotDataEventArgs(byte[] data, int id, string name)
{
this.data = data;
this.id = id;
this.name = name;
timeStamp = DateTime.Now;
}
public byte[] Data
{
get { return data; }
}
public int ID
{
get { return id; }
}
public string Name
{
get { return name; }
}
public DateTime TimeStamp
{
get { return timeStamp; }
}
}
public class YourClass
{
public event EventHandler<GotDataEventArgs> GotData;
protected virtual void OnGotData(GotDataEventArgs e)
{
EventHandler<GotDataEventArgs> eh = GotData;
if (eh != null)
eh(this, e);
}
}
Conclusion
There is a lot more that can be done with events such as cancelable or asynchronous events, but the above examples will cover 99% of use cases.