#1,162 – Virtual Events Support Polymorphism

In C#, polymorphism is implemented using virtual members–which can be methods, properties, indexers or events.

A virtual event has an implementation in the base class that can be overridden in a derived class.  When the event’s add or remove accessors are invoked, the specific accessor used is determined at run-time based on the type of the underlying object.

A virtual event is defined in the base class using the virtual keyword.

        // Code from Dog class
        private EventHandler barked;
        public virtual event EventHandler Barked
        {
            add
            {
                barked += value;
                Console.WriteLine("Dog.Barked add accessor");
            }
            remove
            {
                barked -= value;
                Console.WriteLine("Dog.Barked remove accessor");
            }
        }

A virtual event is overridden in a derived class using the override keyword.

        // Code from Terrier : Dog class
        private EventHandler myBarked;
        public override event EventHandler Barked
        {
            add
            {
                myBarked += value;
                Console.WriteLine("Terrier.Barked add accessor");
            }
            remove
            {
                myBarked -= value;
                Console.WriteLine("Terrier.Barked remove accessor");
            }
        }

Using the event:

            Dog d = new Dog("Bob");
            d.Barked += (s, e) => { Console.WriteLine("Dog.Barked"); };

            Terrier t = new Terrier("Jack");
            t.Barked += (s, e) => { Console.WriteLine("Terrier.Barked"); };

            Dog d2 = t;
            d2.Barked += (s, e) => { Console.WriteLine("Terrier.Barked"); };

1162-001