1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.Collections.Specialized;
6:
7: namespace CSharp.Indexer
8: {
9: public class Employee
10: {
11: private string _name = "";
12:
13: public string Name
14: {
15: get { return _name; }
16: set { _name = value; }
17: }
18:
19: public Employee(string name)
20: {
21: this._name = name;
22: }
23: }
24:
25: public interface IEmployeeInterface
26: {
27: //int Indexer declaration
28: Employee this[int index]
29: {
30: set;
31: }
32:
33: //string indexer declaration
34: Employee this[string name]
35: {
36: get;
37: set;
38: }
39: }
40:
41: public class EmployeeList : IEmployeeInterface
42: {
43: private ListDictionary empDictionary;
44:
45: public EmployeeList()
46: {
47: empDictionary = new ListDictionary();
48: }
49:
50: // The int indexer.
51: public Employee this[int item]
52: {
53: set
54: {
55: if (value != null && !string.IsNullOrEmpty(value.Name))
56: {
57: empDictionary.Add(value.Name, value);
58: }
59: }
60: }
61:
62: // The string indexer.
63: public Employee this[string name]
64: {
65: get { return (Employee)empDictionary[name]; }
66: set { empDictionary.Add(name, value); }
67: }
68: }
69:
70: class Program
71: {
72: static void Main(string[] args)
73: {
74: EmployeeList empList = new EmployeeList();
75:
76: empList[0] = new Employee("david");
77: empList[1] = new Employee("lisa");
78: empList[2] = new Employee("nana");
79:
80: empList["alice"] = new Employee("alice");
81: empList["sam"] = new Employee("sam");
82:
83: Employee alice = empList["alice"];
84: Console.WriteLine("Alice 's name is {0}", alice.Name);
85: Employee nana = empList["nana"];
86: Console.WriteLine("Nana 's name is {0}", nana.Name);
87:
88: Console.ReadLine();
89: }
90: }
91: }