#358 – Virtual Properties Support Polymorphism
July 1, 2011 2 Comments
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