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

[View full width]
 
[View full width]
C:\expt>csc test.cs Test.cs(18,5): error CS0200: Property or indexer 'TestClass.Color' cannot be assigned to graphics/ccc.gif 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.



From Java to C#. A Developers Guide
From Java to C#: A Developers Guide
ISBN: 0321136225
EAN: 2147483647
Year: 2003
Pages: 221
Authors: Heng Ngee Mok

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net