Basic Events

Event is actually just a keyword that you place in front of a delegate to prevent an outside class

from invoking said delegate or tampering with the delegate’s invocation list ( except to subscribe / unsubscribe itself )

In this example, I have a Dog class which will let other classes know each time it barks.
We have once class which is interested in this event – Program Class.

The Program class subscribes to the event “Barking”. For simplicity, I added the public method “ProvokeTheDog()” to fire the event.

Within the Program class, an instance of Dog is created. This instance subscribes to the event by adding the lambda expression to the delegate’s invocation list.
Rottweiler.Barking += () => Console.WriteLine(“Bark”);

The Program class then calls the method “ProvokeTheDog()” to fire the event.
The statement:
if (m_barking != null)
m_barking();
checks the invocation list and fires the event if it has 1 or more subscribers.

We can see that Program was alerted via the trace statement: Console.WriteLine(“Bark”);

To summarize. Event is just a keyword. You append it to delegates to ensure only the class which the delegate belongs to can invoke it and one class cannot tamper with the subscriptions of other classes

basicevent2basicevents1

Posted in Uncategorized

Leave a comment

Design a site like this with WordPress.com
Get started