A standard EventHandler supplies only two items to the method handling the event: the object that caused the event to be fired (the
sender
parameter) and the "normal", basic EventArgs (the
e
parameter). It you don't need to supply more than this, then you can use the Eventargs to create a simple, quick-to-create Event in your class that the outside world can subscribe to:
public event EventHandler MyEvent;
protected virtual void OnMyEvent(EventArgs e)
{
EventHandler eh = MyEvent;
if (eh != null)
{
eh(this, e);
}
}
If you need to provide more than this, then you have to use a Custom EventHandler with your own (derived) EventArgs:
public partial class MyForm : Form
{
public event EventHandler<ChangedArgs> Changed;
private void butGo_Click(object sender, EventArgs e)
{
EventHandler ch = Changed;
if (ch != null)
{
ch(this, new ChangedArgs(tbData.Text));
}
}
}
public partial class ChangedArgs : EventArgs
{
public string strData;
public ChangedArgs(string str)
{
strData = str;
}
}
In answer to your other question:
a) When you want to pass the existing events up from a event handler in your class to the handler for your event. For example, in a Click event, you might pass the EventArgs that your button handler gets to the handler for your classes "DataReady" event.
b) When you don't want to pass the actual class instance to the event handler, but need to pass an object of some form (or pretend it came from a different object that it really does). Never had to use this myself!
c) When you just want to pass a new, clean EventArgs to the handler (probably because you don't think the person writing it can be trusted to check for
null
values. And you are probably right... :sigh: