Indexers and properties are special type members that encapsulate the internal state of a type and provide specialized access to that state. For example, properties are used like fields (variables), but can be specialized to work with one or more fields within a type. Indexers expose an array-like interface to a type, changing the way that type can be used by calling applications. PropertiesA property is an efficient means of exposing a public interface to a type where an attribute of a type has get and set semantics. Properties don't accept parameters, but act more like a smart field and support type encapsulation. In practical usage, a property is accessed as if it were a public field on a type. The only limitation is that a property cannot be passed as a parameter to a method. Listing 2.22 shows how to declare and use a property. Listing 2.22 Declaration and Use of Properties (Properties.cs)using System; class Properties { private static decimal m_myMoney; public static decimal MyMoney { get { return m_myMoney; } set { m_myMoney = value; } } static void Main() { MyMoney = 1000000.00m; Console.WriteLine("MyMoney: {0:$#,###.00}", MyMoney); Console.ReadLine(); } } Most of the time, a property will be declared exactly like MyMoney in Listing 2.22. Properties without a get accessor are write-only and properties without a set accessor are read-only. IndexersIndexers allow types to act like arrays or collections. They accept one or more parameters and return a specified type. Like properties, they also support get and set semantics. Listing 2.23 demonstrates how to declare and use an indexer. Listing 2.23 Declaration and Use of Indexers (Indexers.cs)using System; class MyType { int[] myInts = { 0, 0, 0 }; public int this[int i] { get { return i < myInts.Length ? myInts[i] : -1; } set { if (i < myInts.Length) { myInts[i] = value; } } } } class Indexers { static void Main() { MyType myType = new MyType(); for (int i=0; i < 5; i++) { myType[i] = i+1; Console.WriteLine("myType[{0}] = {1}", i, myType[i]); } Console.ReadLine(); } } The indexer in Listing 2.23 lets the MyType class act just like an array. The get and set accessors protect the integrity of the data and avoid errors. A given implementation will depend on how the information is stored. A significant benefit of both indexers and properties is that the internal data implementation may change, but the public interface won't. |