Chapter 20. C# propertiesC# 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.
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]
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]
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 |