#355 – Use the new Keyword to Replace a Property in a Base Class
June 28, 2011 1 Comment
A derived class inherits data and behavior from its parent class.
There are times when you might want to replace property accessors in a base class with new accessors in the derived class, using the same property name. You can do this using the new keyword.
Assume a Dog class has a Temperament property:
protected string temperament; public string Temperament { get { return string.Format("{0} is {1}", Name, temperament); } set { temperament = value.ToLower(); } }
You can provide a new version of this property in a class that derives from Dog, using the new keyword. This new property hides the property in the base class.
public new string Temperament { get { return string.Format("Terrier {0} is {1}", Name, temperament); } set { temperament = value.ToUpper(); } }
The get/set accessors used will now depend on the type of the object.