#1,161 – Explicit Implementation of Events in Interface

If you implement an event defined in an interface explicitly, you must use event accessor syntax, defining both add and remove accessors.

    public interface IDogEvents
    {
        event EventHandler Barked;
        event EventHandler Escaped;
    }

    public class Dog : IDogEvents
    {
        public string Name { get; set; }
        public bool IsPresent { get; set; }

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

        public void Bark()
        {
            Console.WriteLine("Woof");
            if (IsPresent)
                barked(this, EventArgs.Empty);
            else
                escaped(this, EventArgs.Empty);
        }

        private EventHandler barked;
        event EventHandler IDogEvents.Barked
        {
            add { barked += value; }
            remove { barked -= value; }
        }

        private EventHandler escaped;
        event EventHandler IDogEvents.Escaped
        {
            add { escaped += value; }
            remove { escaped -= value; }
        }
    }

You can then add an event handler by using an interface reference.

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

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

Leave a comment