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
MediumCreate a method named CreateFruitInventory that:
- Creates a new Dictionary with string keys and int values
- Adds the following fruits and quantities:
- "Apple" with a quantity of 5
- "Banana" with a quantity of 10
- "Orange" with a quantity of 7
- 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}");
}
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety9HashMap Part 1
What is a HashMap?Declare a HashMapCheck If Key ExistsAccessing ValuesModifying DictionariesRecap - HashMap