20.3. Inheritance of properties

Like other class members, properties can be inherited to subclasses. You can override properties just as you would override other methods. It is possible to just override the get section of a property and inherit the set section, and vice versa.

The example below shows two classes, Parent and Child. Child is the subclass of Parent and inherits both the protected field, MyColor, and the public property, Color.

 1: using System;
 2:
 3: public class Parent{
 4:   protected string MyColor = "yellow";
 5:
 6:   // property Color
 7:   public virtual string Color{ 8: get{ 9: Console.WriteLine("running GET of Parent"); 10: return MyColor; 11: } 12: set{ 13: Console.WriteLine("running SET of Parent"); 14: MyColor = value; 15: } 16: ...

Get From Java to C#: A Developer's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.