O'Reilly logo

From Java to C#: A Developer's Guide by Heng Ngee Mok

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required