Complete C# Tutorial

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:

  1. Key = A unique identifier (like ID, name, etc.).
  2. 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! πŸŽοΈπŸ’¨

πŸ€” Why is Generics Dictionary<TKey, TValue> in C# Important?

  1. Fast searching – Find values instantly using keys.
  2. Unique keys – Prevent duplicate entries automatically.
  3. Efficient memory use – Stores large amounts of data without wasted space.
  4. 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, and Charlie) 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;
				
			
  1. The System namespace is included so we can use Console.WriteLine().

  2. 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>();
				
			
  1. Dictionary<string, int> β†’ A dictionary where the key is a string (student’s name) and the value is an int (student’s score).
  2. studentScores β†’ The name of our dictionary.
  3. 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);
				
			
  1. Add("Alice", 95) β†’ Adds “Alice” as the key and 95 as the value.

  2. Add("Bob", 88) β†’ Adds “Bob” as the key and 88 as the value.

  3. 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"]);
				
			
  1. We retrieve Alice’s score using studentScores["Alice"].

  2. Since "Alice" is a key in the dictionary, it returns the value 95.

  3. 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! πŸš€

MethodDescriptionExample
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! πŸ”₯

Leave a Comment

Share this Doc

Generics Dictionary<TKey, TValue>

Or copy link