Chapter 20. C properties


Chapter 20. C# properties

C# properties are convenient alternatives to accessor (getter) and mutator (setter) methods in a class. It is something new and extremely useful. Do not confuse the term 'properties' in C# with the term 'properties' commonly used in OO nomenclature . Here, a property does not refer to a characteristic of a class, [1] although a C# property is still a class member.

[1] In OO literature, you will often see statements like 'a class contains properties, also known as attributes, which represent characteristics of a class'. properties and attributes in C# have different meanings. You use the term 'fields' or 'field variables ' to represent the characteristics of a class.

What are called instance or static variables in Java, are called instance or static fields in C#. Because fields are often made private members of a class, accessor and mutator methods are written for external parties to retrieve or set their values. [2]

[2] In a good clean implementation (be it in Java or C#, or any other OO programming language), fields should be properly encapsulated in a class by making them private. In the event that their values are to be 'exposed' to the external world, you write accessor methods for them. In fact, your OO lecturers will tell you that none of your fields should be made public, and they are right.

In C#, you can still write accessor and mutator methods to get or set a field's value, but you can also make use of properties. You can think of properties as a more elegant substitute for accessor and mutator methods which you can use to read/write to private fields of a class. [3]

[3] I have seen literature referring to properties as 'smart fields'. Properties are not really fields, but behave like fields to external classes “ hence that name .

Here is an example of a class with a private field ( MyColor ) together with accessor and mutator methods. It should look familiar:

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

Output:

 c:\expt>test yellow blue 


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