using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace EmployeeDict { class Program { static void Main(string[] args) { // Create a dictionary of employees, keyed on their staff number. GenDictionary staff = new GenDictionary(100); // Add some employees. staff["007"] = new Employee("James Bond"); staff["010"] = new Employee("Lee Trundle"); // Get an employee. Employee emp = staff["010"]; Console.WriteLine("In GenDictionary, Employee 010 is {0}.", emp); Console.ReadLine(); } } public class Employee { private string name; public Employee(string name) { this.name = name; } public override string ToString() { return name; } } public class GenDictionary { // Nested class, to represent one key/value entry in the dictionary. struct Entry { public K key; public V value; public Entry(K key, V value) { this.key = key; this.value = value; } }; // The dictionary holds an array of entries. Each entry has a key and a value. private Entry[] entries; private int numEntries; private int maxEntries; public GenDictionary(int size) { entries = new Entry[size]; numEntries = 0; maxEntries = size; } public bool Contains(K key) { // Loop through all entries, to find a key that matches the parameter key. foreach (Entry entry in entries) { if (entry.key.Equals(key)) return true; } return false; } public V this[K key] { get { // Loop through all entries, to find a key that matches the parameter key. Return the value for that entry. foreach (Entry entry in entries) { if (entry.key.Equals(key)) return entry.value; } // Key not found, so return default value for the "value type". return default(V); } set { // Loop through all entries, to find a key that matches the parameter key. Set the value for that entry. for (int i = 0; i < numEntries; i++) { Entry entry = entries[i]; if (entry.key.Equals(key)) { entry.value = value; return; } } // Key not found, so add new entry at end of array (if not already full). if (numEntries < maxEntries) { entries[numEntries++] = new Entry(key, value); } } } } }