#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
        {
            get
            {
                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
        {
            get
            {
                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 .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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers