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

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