#1,158 – Events vs. Delegates, part I

You’ll typically define an event rather than using a public delegate.  Although either method will work, events provide some benefits over using delegates directly.

Below, we define a delegate type and a Barked event of that type in a Dog class:

    public delegate void DogDelegate(string dogName);

    public class Dog
    {
        public string Name { get; set; }

        public Dog(string name)
        {
            Name = name;
        }

        public event DogDelegate Barked = delegate { };

        public void Bark()
        {
            Console.WriteLine("Woof");
            Barked(Name);
        }
    }

We can now handle the event as follows:

        static void Main(string[] args)
        {
            Dog d = new Dog("Bob");
            d.Barked += d_Barked;
            d.Bark();

            Console.ReadLine();
        }

        static void d_Barked(string dogName)
        {
            Console.WriteLine(dogName + " just barked");
        }

1158-001
This code would all work the same if we simply removed the event keyword, making the delegate available to the client code.  (See part II for more information).

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.

2 Responses to #1,158 – Events vs. Delegates, part I

  1. Pingback: Dew Drop – August 13, 2014 (#1835) | Morning Dew

  2. Pingback: Visual Studio Color Theme - The Daily Six Pack

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: