#348 – Virtual Methods Support Polymorphism

In C#, polymorphism is implemented using virtual methods.  A virtual method has an implementation in the base class that can be overridden in a derived class.  When the method is invoked on an object of the base class’ type, the specific method to be called is determined at run-time based on the type of the underlying object.

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

    public class Dog
    {
        public virtual void Bark()
        {
            Console.WriteLine("Generic dog {0} says Woof", Name);
        }
    }

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

    public class Terrier : Dog
    {
        public override void Bark()
        {
            Console.WriteLine("Terrier {0} is barking", Name);
        }
    }

This allows polymorphic behavior when invoking the Bark method.

            Dog jack = new Terrier("Jack", 15);
            jack.Bark();       // Terrier.Bark called, rather than Dog.Bark

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

2 Responses to #348 – Virtual Methods Support Polymorphism

  1. Pingback: #618 – Use the base Keyword to Call A Method in the Base Class « 2,000 Things You Should Know About C#

  2. Pingback: #770 – Use Intellisense to Get List of Methods to Override « 2,000 Things You Should Know About C#

Leave a comment