c#:
[quoted text, click to view] "Flare" <nomail@sorry.dk> wrote in message
news:OgyoyObSEHA.2612@TK2MSFTNGP10.phx.gbl...
> Hi i have a qusstion about events and delegates. Especially the precis
> role
> of the Event.
>
> Eg. We have a class wich want to fire events so we declare:
>
> public delegate void TestEventHandler(object sender, EventArgs arg);
> public event TestEventHandler Test;
>
> And fire the event with
>
> if(Test != null)
> Test(this, new EventArg());
>
> Is the right:
> Test is actually a MultiCast delgate? Debugger says it is! OK.
>
> Buth then why use the event keyword in front of the Test and insted not
> just:
>
> public delegate void TestEventHandler(object sender, EventArgs arg);
> public TestEventHandler Test;
>
> And fire the event with
> if(Test != null)
> Test(this, new EventArg());
>
> It work fine. Why do we need the event keyword? Clearly there is a reason.
> Someone who can tell me?
The event keyword creates an event property(literally, event results in two
methods, add_EventName and remove_EventName, which are used to add and
remove listener delegates. The spec also defines a protected raise_EvetnName
accessor, but C# nor VB uses it to my knowledge, C++ does I think).
Basically it hides the delegate from outsiders. It restricts raising the
event to your local class and keeps others from modifying(or accessing) the
delegate list, that combined with the += and -= C# syntax and metadata
declaring the member is an event, not just a delegate are the primary
reasons. Imagine the fun if external code could wipe out all listeners or
fake events being raised.
I'd never recommend using direct delegate fields.
[quoted text, click to view] >
> reagards
> Anders
>
>