[Mono-list] Little question ...
Jonathan Gilbert
2a5gjx302@sneakemail.com
Sun, 08 Feb 2004 11:07:35
At 11:21 AM 07/02/2004 -0500, you wrote:
>Hey,
>> Only one little question: What are the main differences between using
>> "event" keyword or not when creating delegates?
>>
>> Example:
>>
>> delegate void ProbeDelegate (string msg);
>>
>> ProbeDelegate d1;
>> event ProbeDelegate d2;
>
>events can notify more than one function, a delegate only points to a
>single method.
>
>So you can have multiple "listeners".
Actually, this isn't quite correct. Events use delegates to perform their
task -- a delegate which points to multiple targets is called a "multicast
delegate". In C#, the 'event' keyword is more of an access modifier. Behind
the scenes, without the 'event' keyword, the delegate is just a field whose
value is the delegate type. The field can be erased, or completely
reassigned. However, when you add the 'event' keyword, it translates the
source code to something like this:
class MyClass
{
private ProbeDelegate d2;
public void addHandler_d2(ProbeDelegate f) { d2 += f; }
public void delHandler_d2(ProbeDelegate f) { d2 -= f; }
}
..where, of course, addHandler and delHandler map to the += and -= C#
operations on the event. As you can see, with the 'event' keyword, it is
impossible for code outside of the class to do such things as invoking the
function(s) it refers to, or retrieving the list of functions that the
delegate points at.
Code without the 'event' keyword will work identically, except that code
outside of the class is "permitted" to, well, screw things up :-) For
instance, a separate class could decide that it wanted to be the only class
receiving events, and could clear all other callers from the delegate. With
the 'event' keyword, this is impossible.
Jonathan