Free mag vol1 | Page 462

CHAPTER 11  ADVANCED C# LANGUAGE FEATURES public class PersonCollection : IEnumerable { private Dictionary listPeople = new Dictionary(); // This indexer returns a person based on a string index. public Person this[string name] { get { return (Person)listPeople[name]; } set { listPeople[name] = value; } } public void ClearPeople() { listPeople.Clear(); } public int Count { get { return listPeople.Count; } } } IEnumerator IEnumerable.GetEnumerator() { return listPeople.GetEnumerator(); } The caller would now be able to interact with the contained Person objects as shown here: static void Main(string[] args) { Console.WriteLine("***** Fun with Indexers *****\n"); PersonCollection myPeople = new PersonCollection(); myPeople["Homer"] = new Person("Homer", "Simpson", 40); myPeople["Marge"] = new Person("Marge", "Simpson", 38); // Get "Homer" and print data. Person homer = myPeople["Homer"]; Console.WriteLine(homer.ToString()); } Console.ReadLine(); Again, if you were to use the generic Dictionary type directly, you’d gain the indexer method functionality out of the box, without building a custom, nongeneric class supporting a string indexer. Nevertheless, do understand that the data type of any indexer will be based on how the supporting collection type allows the caller to retrieve subitems.  Source Code The StringIndexer project is located under the Chapter 11 subdirectory. 402