C# Dictionary Methods Guide
C# Dictionary Methods Guide
can you tell me about c# dictionaries and some common methods for c# dictionaries? basically
everything I need to know as a beginner
C# Dictionaries Overview
A dictionary in C# is a collection type that stores key-value pairs. It's part of the
System.Collections.Generic namespace. Each key in a dictionary must be unique, and each key is
associated with a value.
Namespace: `System.Collections.Generic`
Class: `Dictionary<TKey, TValue>`
Key Characteristics
Creating a Dictionary
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create a dictionary
Dictionary<int, string> students = new Dictionary<int, string>();
// Accessing values
Console.WriteLine(students[1]); // Output: Alice
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/4
Here’s a list of some commonly used methods and properties:
1. Add(Key, Value)
csharp
dictionary.Add(4, "David");
2. ContainsKey(Key)
csharp
3. ContainsValue(Value)
csharp
4. Remove(Key)
csharp
dictionary.Remove(3);
Tries to get the value associated with the key. If the key exists, returns true and assigns the value to
`out`. Otherwise, returns false.
csharp
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/4
Console.WriteLine(value); // Output: Alice
}
6. Count
csharp
csharp
8. Clear()
csharp
dictionary.Clear();
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Create and populate dictionary
Dictionary<string, int> inventory = new Dictionary<string, int>
{
{ "Apples", 10 },
{ "Oranges", 5 },
{ "Bananas", 20 }
};
// Update value
inventory["Oranges"] += 5;
// Remove an item
inventory.Remove("Bananas");
// Display inventory
foreach (var item in inventory)
{
Console.WriteLine($"{item.Key}: {item.Value}");
}
}
}
Output:
makefile
Apples: 10
Apples: 10
Oranges: 10
1. Key Equality: The type of the key must implement a proper equality comparison (usually
`Equals()` and `GetHashCode()`).
2. Exceptions: Adding a duplicate key with `Add()` throws an exception. Use `TryAdd()` or
`ContainsKey()` to avoid this.
3. Default Values: Accessing a non-existent key with `dictionary[key]` throws a
`KeyNotFoundException`. Use `TryGetValue()` instead.
Let me know if you'd like examples or explanations of any specific part in more depth!
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/4