#378 – Implementing an Event

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: