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 the same private field, although this is usually not done.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.28.110