Dictionary<TKey, TValue> is a collection that stores data as key-value pairs. Because keys and values are paired together, it's great for mapping data like username to role, product code to price, or country to capital.
csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> productPrices = new Dictionary<string, int>();
productPrices.Add("Laptop", 1200);
productPrices.Add("Mouse", 25);
productPrices.Add("Keyboard", 80);
Console.WriteLine(productPrices["Laptop"]);
if (productPrices.ContainsKey("Mouse"))
{
Console.WriteLine($"Mouse price: {productPrices["Mouse"]}");
}
}
}Watch out for this
productPrices["Laptop"]uses the key to fetch the value.- Accessing a key that doesn't exist can throw an error. That's why it's safer to check first with
ContainsKey(). - Dictionary keys must be unique. Adding a duplicate key can cause an error.
You should see
1200 Mouse price: 25