Chapter 8 Advanced C#
Chapter Objectives Indexer Overloading Operators Customized Conversion Building a Custom Indexer Overloading Operators +, ==, <, >=, Customized Conversion
Indexers Indexers provide access to an object's members via a subscript operator Indexers permit instances of a class or struct to be indexed in the same way as arrays. Indexers are similar to properties except that their accessors take parameters. Defining an indexer allows you to create classes that act like "virtual arrays." Instances of that class can be accessed using the [ ] array access operator. Defining an indexer in C# is similar to defining operator [ ] in C++, but is considerably more flexible. Use indexers only when the array-like abstraction makes sense.
Declaration get { return items[key]; } set { items[key] = value; } public object this[int key] { get { return items[key]; } set { items[key] = value; } } Indexers may be overloaded and abstract/virtual keywords can also be used public abstract object this[int key] get ; set ;
Example class MyClass { private string[ ] data = new string[5]; public string this [int index] get return data[index]; } set data[index] = value;
Client class MyClient { public static void Main() MyClass mc = new MyClass(); mc[0] = "Scott"; mc[1] = "A3-126"; mc[2] = "35th Street"; mc[3] = "Boston"; mc[4] = "USA"; Console.WriteLine("{0},{1},{2},{3},{4}", mc[0],mc[1],mc[2],mc[3],mc[4]); }
telPhone Class public class telPhone { private int phoneno; private string Name; public telPhone() phoneno = 0; Name = null; } public telPhone(int p, string n) phoneno = p; Name = n; public int Phone get { return phoneno; }
Directory Class using System; using System.Collections; using System.Collections.Specialized; public class Directory { // This class maintains a telephone directory private ListDictionary telDir; public Directory() telDir = new ListDictionary(); }
Directory Class… // Overloaded Indexer - The string indexer. public telPhone this[string name] { get { return (telPhone)telDir[name];} set { telDir.Add(name, value);} } // Overloaded Indexer - The int indexer. public telPhone this[int item] get { return (telPhone)telDir[item];} set { telDir.Add(item, value);}
Client { public static void Main(string[] args) public class TelephoneApp { public static void Main(string[] args) Directory d = new Directory(); d["Scott"] = new telPhone(26613237,"Scott"); d["Allen"] = new telPhone(56789456,"Allen"); telPhone scotttel = d["Scott"]; Console.WriteLine("Telephone No. of Allen is = {0}", scotttel.Phone); Console.WriteLine("Telephone No. of Allen is = {0}", d["Scott"]); }
Refer to OverloadOps folder Operator Overloading Same as C++ public struct Point { public int x, y; …… public static Point operator + (Point p1, Point p2) return new Point(p1.x + p2.x, p1.y + p2.y); } public static bool operator == (Point p1, Point p2) return p1.Equals(p2); } Refer to OverloadOps folder
Custom Type Conversion Square sq; ….. Rectangle rect = (Rectangle) sq;