#358 – Virtual Properties Support Polymorphism

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

A virtual property has an implementation in the base class that can be overridden in a derived class.  When the property is read or written, the get or set accessor that is used is determined at run-time based on the type of the underlying object.

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

        protected string temperament;
        public virtual string Temperament
                return string.Format("{0} is {1}", Name, temperament);

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

        public override string Temperament
                return string.Format("Terrier {0} is {1}", Name, temperament);

Using the property:

            Dog kirby = new Dog("Kirby", 15);
            Console.WriteLine(kirby.Temperament);  // Kirby is Average

            Dog jack = new Terrier("Jack", 15);
            Console.WriteLine(jack.Temperament);   // Terrier Jack is Surly

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

2 Responses to #358 – Virtual Properties Support Polymorphism

  1. Pingback: #684 – Hidden Base Class Members Aren’t Really Hidden « 2,000 Things You Should Know About C#

  2. stravinsky7 says:

    Ah, I see.. question from 2 posts ago answered, slantwise.

    Just keep reading.. Just keep reading.. What do we do? we Read!!

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: