Menu
Coddy logo textTech

Declare a HashMap

Part of the Logic & Flow section of Coddy's C# journey — lesson 47 of 66.

In C#, the equivalent of a HashMap is called a Dictionary. It allows you to store key-value pairs for efficient lookup.

First, let's create an empty Dictionary:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>();

This creates a Dictionary where the keys are strings (fruit names) and the values are integers (quantity).

Now, let's add some items to our Dictionary:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

After executing the above code, our fruitInventory contains:

  • "Apple" → 10
  • "Banana" → 15

You can also initialize a Dictionary with values:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};
challenge icon

Challenge

Medium

Create a method named CreateFruitInventory that:

  1. Creates a new Dictionary with string keys and int values
  2. Adds the following fruits and quantities: 
    • "Apple" with a quantity of 5
    • "Banana" with a quantity of 10
    • "Orange" with a quantity of 7
  3. Returns the created Dictionary

Cheat sheet

In C#, a Dictionary stores key-value pairs for efficient lookup:

Create an empty Dictionary:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>();

Add items to a Dictionary:

fruitInventory.Add("Apple", 10);
fruitInventory.Add("Banana", 15);

Initialize a Dictionary with values:

Dictionary<string, int> fruitInventory = new Dictionary<string, int>()
{
    { "Apple", 10 },
    { "Banana", 15 }
};

Try it yourself

using System;
using System.Collections.Generic;

class Program
{
    public static Dictionary<string, int> CreateFruitInventory()
    {
        // Write your code here
    }
    
    static void Main(string[] args)
    {
        Dictionary<string, int> inventory = CreateFruitInventory();
        
        // Display the inventory
        foreach (var item in inventory)
        {
            Console.WriteLine($"{item.Key}: {item.Value}");
        }
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow