20.2. Having only either the get or set section

If MyColor only is to be read, and not altered via the Color property, you can exclude the set section in the property declaration. When declaring properties, you can exclude either section, but not both.

Let's comment out the set section in the class above:

 7:   public string Color{
 8:     get{
 9:       return MyColor;
10:     }
11:   /* set{
12:       MyColor = value;
13:     } */
14:   }

Compiling the program gives an error this time because the code in Main() still tries to assign a value to the Color property (on line 18):

C:\expt>csc test.cs
Test.cs(18,5): error CS0200: Property or indexer 'TestClass.Color' cannot be assigned to
 – it is read only

It is also possible to create two or more public properties to access ...

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.