#378 – Implementing an Event
July 29, 2011 Leave a comment
You can subscribe to an event in a class by writing an event handler. You can also implement events in your own class.
An event is just a class member that is an instance of a delegate type and is declared using the event keyword.
Suppose you’ve defined a delegate type that takes a string parameter:
public delegate void StringHandlerDelegate(string s);
You can now use this delegate type to define an event in a class. The event is just an instance of the delegate type.
public event StringHandlerDelegate Barked;
You can now add code in your class to raise the event. We fire the Barked event from the Bark method.
public void Bark(string barkSound) { Console.WriteLine(barkSound); // Raise the event if (Barked != null) Barked(barkSound); }
Before invoking the delegate, we make sure it’s not null, to avoid an exception at run-time.