Creating Dictionaries

You can also make a class that derives from DictionaryBase. This way, you can access each element by key (usually of type string) and they will return its associated value. When calling an item from a dictionary, we can call it by its key and not by its index. The following code creates a class that implements DictionaryBase.

using System.Collections;
 
namespace DictionariesDemo
{
    public class Animal
    {
        public string manone { get; set; }
        public int notone { get; set; }
        public double Height { get; set; }
 
        public Animal(string name, int age, double height)
        {
            manone = name;
            notone = age;
            Height = height;
        }
    }
 
    public class Animals : DictionaryBase                       
    {                                                           
        public void Add(string key, Animal newAnimalnewAnimal)  
        {                                                       
            Dictionary.Add(key, newAnimalnewAnimal);            
        }                                                       
                                                                
        public void Remove(string key)                          
        {                                                       
            Dictionary.Remove(key);                             
        }                                                       
                                                                
        public Animal this[string key]                          
        {                                                       
            get { return (Animal)Dictionary[key]; }             
            set { Dictionary[key] = value; }                    
        }                                                       
    }                                                           
}

Example 1 – Creating Your Own Dictionary

We defined a class Animal that will be used by our dictionary class. We then create a class that inherits the DictionaryBase class. You can now define the methods for adding and removing dictionary entries. The Add method requires a string key and the Animal object we are adding to the dictionary. We used the Dictionary property of the DictionaryBase class to add the entry to the dictionary using the passed arguments. The Remove method only requires the key of the object we are trying to remove. We also use the Dictionaryproperty to remove items. We defined an indexer that accepts a string key instead of an int value.

Let’s create a class that demonstrates the capability of our dictionary class.

using System;
 
namespace DictionariesDemo
{
    public class Program
    {
        public static void Main()
        {
            Animals animalDictionary = new Animals();
 
            animalDictionary.Add("Animal1", new Animal("John", 10, 100));
            animalDictionary.Add("Animal2", new Animal("Sussy", 5, 10)); 
            animalDictionary.Add("Animal3", new Animal("Frank", 3, 5));  
            animalDictionary.Add("Animal4", new Animal("Mark", 7, 15));  
 
            Console.WriteLine("Accessing entries by their keys");
 
            for (int i = 0; i < animalDictionary.Count; i++)
            {
                Console.WriteLine(animalDictionary["Animal" + (i + 1)].Name);
            }
 
            animalDictionary.Remove("Animal3");
            Console.WriteLine("\nFrank was removed from the dictionary.");
 
            Console.WriteLine("\nIterating using foreach loop.");
            foreach (DictionaryEntry animal in animalDictionary)
            {
                Console.WriteLine((animal.Value as Animal).Name);
            }
        }
    }
}

Example 2 – Custom Dictionary In Action

Accessing entries by their keys
John
Sussy
Frank
Mark

Frank was removed from the dictionary.

Iterating using foreach loop.
John
Mark
Sussy

We created a new instance of the Animals dictionary class. We then add some instances to it and their respective keys. We first demonstrated using a for loop that we can access each of its entries by using their keys as their index. We used the Remove() method to remove the third entry in the dictionary using its key. We then use a foreach loop to try to read all the values. But you might notice that something is different. We used the DictionaryEntry as the type because each item in a dictionary class has that type instead of, for example, an Animal. Tha actual object is inside the Value property of the DictionaryEntry. We cast this value to its appropriate type. We will learn next how we can avoid using a DictionaryEntry and use the actual type by using iterators.