Generics Dictionary<TKey, TValue> in C# - Easy Guide with Examples
π Introduction
Have you ever needed to store key-value pairs in C#? π€
For example, mapping student names to their scores, product IDs to product names, or employee IDs to salaries? In such cases, using a Generics Dictionary<TKey, TValue> in C# is the best choice! π
A Dictionary<TKey, TValue>
stores data in a key-value format where:
- Key = A unique identifier (like ID, name, etc.).
- Value = The data associated with the key (like score, price, etc.).
Unlike lists, Dictionaries allow you to quickly find, add, or remove elements using keys instead of index positions! ποΈπ¨
π What You Are Going to Learn in This Lesson?
βοΈ What is Generics Dictionary<TKey, TValue> in C#?
βοΈ Why and when should you use it?
βοΈ Basic syntax and structure.
βοΈ Important methods (Add, Remove, Contains, etc.).
βοΈ A real-world example to make things easy.
βοΈ A complete program with detailed explanations.
Let’s go! π
π€ Why is Generics Dictionary<TKey, TValue> in C# Important?
- Fast searching β Find values instantly using keys.
- Unique keys β Prevent duplicate entries automatically.
- Efficient memory use β Stores large amounts of data without wasted space.
- Easy to use β No need to manage index positions like
List<T>
.
Now, letβs see how it works! π
π οΈ Syntax of Generics Dictionary<TKey, TValue> in C#
Hereβs how you declare a Dictionary in C#:
Dictionary<TKey, TValue> dictionaryName = new Dictionary<TKey, TValue>();
π Explanation:
TKey
β The type of keys (e.g.,int
,string
).TValue
β The type of values (e.g.,double
,string
).dictionaryName
β The name of the dictionary.
Example: Creating a Dictionary of Student Scores
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a Dictionary to store student scores
Dictionary<string, int> studentScores = new Dictionary<string, int>();
studentScores.Add("Alice", 95);
studentScores.Add("Bob", 88);
studentScores.Add("Charlie", 92);
Console.WriteLine("Alice's Score: " + studentScores["Alice"]);
}
}
π₯οΈ Output:
Alice's Score: 95
1οΈβ£ What is happening in this code?
We are using a Dictionary<string, int> to store student names as keys and their scores as values.
We then add three students (
Alice
,Bob
, andCharlie
) along with their scores.Finally, we print Alice’s score using her name as the key.
π οΈ Code Breakdown: Line by Line
1οΈβ£ using System;
& using System.Collections.Generic;
using System;
using System.Collections.Generic;
-
The System namespace is included so we can use
Console.WriteLine()
. -
The System.Collections.Generic namespace is required because
Dictionary<TKey, TValue>
is part of the Generic Collections in C#.
2οΈβ£ Creating a Dictionary
Dictionary<string, int> studentScores = new Dictionary<string, int>();
- Dictionary<string, int> β A dictionary where the key is a
string
(student’s name) and the value is anint
(student’s score). - studentScores β The name of our dictionary.
- new Dictionary<string, int>() β Initializes an empty dictionary.
3οΈβ£ Adding Key-Value Pairs (Student Names & Scores)
studentScores.Add("Alice", 95);
studentScores.Add("Bob", 88);
studentScores.Add("Charlie", 92);
-
Add("Alice", 95)
β Adds “Alice” as the key and 95 as the value. -
Add("Bob", 88)
β Adds “Bob” as the key and 88 as the value. -
Add("Charlie", 92)
β Adds “Charlie” as the key and 92 as the value.
π Now, our dictionary looks like this internally:
{
"Alice": 95,
"Bob": 88,
"Charlie": 92
}
4οΈβ£ Accessing a Value from Dictionary
Console.WriteLine("Alice's Score: " + studentScores["Alice"]);
We retrieve Alice’s score using
studentScores["Alice"]
.Since
"Alice"
is a key in the dictionary, it returns the value 95.Finally, we print “Alice’s Score: 95”.
π₯οΈ Output of the Program
Alice's Score: 95
π Fast, simple, and effective! Instead of searching for a value, we directly fetch it using the key.
What Happens If the Key Doesn’t Exist?
Let’s say we try to access "David"
like this:
Console.WriteLine(studentScores["David"]);
Since "David"
is not in the dictionary, the program will throw an error:
Unhandled Exception: System.Collections.Generic.KeyNotFoundException
π₯ Solution?
Use ContainsKey()
before accessing a key:
if (studentScores.ContainsKey("David"))
{
Console.WriteLine(studentScores["David"]);
}
else
{
Console.WriteLine("Student not found!");
}
π₯οΈ Output (If David isn’t in the dictionary)
Student not found!
π Now, the program is safe! β
π Important Methods of Generics Dictionary<TKey, TValue> in C#
Hereβs a cheat sheet of the most used methods! π
Method | Description | Example |
---|---|---|
Add(TKey, TValue) | Adds a new key-value pair. | dictionary.Add("Alice", 95); |
Remove(TKey) | Removes an item by key. | dictionary.Remove("Alice"); |
ContainsKey(TKey) | Checks if a key exists. | dictionary.ContainsKey("Alice"); |
ContainsValue(TValue) | Checks if a value exists. | dictionary.ContainsValue(95); |
Count (Property) | Returns the number of items. | int size = dictionary.Count; |
TryGetValue(TKey, out TValue) | Safely gets a value. | dictionary.TryGetValue("Alice", out int score); |
π‘ Example 1: Working with Dictionary Methods
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, string> employees = new Dictionary<int, string>();
employees.Add(101, "John");
employees.Add(102, "Sara");
employees.Add(103, "Mike");
Console.WriteLine("Employee 102: " + employees[102]);
employees.Remove(101);
Console.WriteLine("Contains 101? " + employees.ContainsKey(101));
}
}
π₯οΈ Output:
Employee 102: Sara
Contains 101? False
π₯ See how fast and easy it is to store and retrieve key-value pairs?
π Real-World Example: Product Price List πͺ
Letβs say youβre building a shopping app where you store product prices.
A Dictionary<string, double>
would be perfect for this!
Β
π» Code Example: Storing Product Prices
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<string, double> productPrices = new Dictionary<string, double>
{
{ "Laptop", 999.99 },
{ "Phone", 499.50 },
{ "Tablet", 299.99 }
};
Console.WriteLine("π± Phone Price: $" + productPrices["Phone"]);
productPrices["Phone"] = 450.00; // Updating price
Console.WriteLine("π± Updated Phone Price: $" + productPrices["Phone"]);
}
}
π₯οΈ Output:
π± Phone Price: $499.5
π± Updated Phone Price: $450
π― See how easy it is to store and update product prices? π
π― Conclusion
Today, you learned:
β‘οΈ Dictionary<TKey, TValue>
stores key-value pairs efficiently.
β‘οΈ Fast lookups using keys instead of searching lists.
β‘οΈ Common methods like Add()
, Remove()
, and ContainsKey()
.
β‘οΈ A real-world example of storing product prices.
π₯ Now, go and try it out! Play around with different key-value pairs and build something cool! π
Β
βοΈ Next What?
Excited to learn more? π
In the next chapter, weβll explore Generics Queue<T> in C#, which is perfect for handling FIFO (First-In, First-Out) operations! Stay tuned! π
Β
π₯ Keep learning, keep growing, and keep coding! π₯