#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()

We can now handle the event as follows:

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


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

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).


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Connecting to %s

%d bloggers like this: