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.1. Properties as a replacement for accessor and mutator methods

In C#, instead of writing accessor and mutator methods, you can use a special class member called a property. I have altered the class above to replace the accessor/mutator methods with a public property called Color. This property represents the private field MyColor. Study the code below.

 1: using System;
 2:
 3: public class TestClass{
 4:   private string MyColor = "yellow";
 5:
 6:   // property Color
 7:   public string Color{
 8:     get{
 9:       return MyColor;
10:     }
11:     set{
12:       MyColor = value;
13:     }
14:   }
15:   public static void Main(){
16:     TestClass c = new TestClass();
17:     Console.WriteLine(c.Color); // get
18:     c.Color = "blue"; // set 19: Console.WriteLine(c.Color); // get 20: } 21: } ...

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