#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();
        }
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: