C# delegate v.s. EventHandler
The difference between event and delegate is that:
event declaration adds a layer of protection on the delegate instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list, and only allows adding or removing targets from the invocation list
See What are the differences between delegates and events?
2) As I see it, your subscriber should not change delegates freely. One subscriber can assign =
to it instead of adding +=
. This will assign a new delegate, therefore, the previous delegate with its invocation list will be lost and previous subscribers will not be called anymore. So you should use Event for sure. Or you can change your code to make your delegate private and write additional functions for manipulating it to define your own event behavior.
//preventing direct assignment
private myDelegate del ;
public void AddCallback(myDelegate m){
del += m;
}
public void RemoveCallback(myDelegate m){
del -= m;
}
//or
public static trap operator +(trap x,myDelegate m){
x.AddCallback(m);
return x;
}
public static trap operator -(trap x, myDelegate m)
{
x.RemoveCallback(m);
return x;
}
//usage
//t.AddCallback(new trap.myDelegate(notify));
t+=new trap.myDelegate(notify);
It is much better to use an event
for your example.
An
event
is understood by the Visual Studio Form and WPF designers, so you can use the IDE to subscribe to events.When raising
events
, there is no need for you to write your ownforeach
handling to iterate through them.events
are the way that most programmers will expect this functionality to be accessed.If you use a delegate, the consuming code can mess around with it in ways that you will want to prevent (such as resetting its invocation list).
events
do not allow that to happen.
As for your second question: Using an event
you would create a class derived from EventArgs
to hold the data, and pass that to the event when you raise it. The consumer will then have access to it.
See here for details: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx