- Author

- Name
- Nelson Silva
- Social
Introduction
In the world of programming, we frequently encounter situations where it is necessary to store data in a structured way. This is where dictionaries in C# come into play, providing an efficient way to store and retrieve data.
- What are Dictionaries?
- Common Methods and Properties
- Working with Dictionaries in C#
- Practical Case: Storing Application Settings
What are Dictionaries?
Dictionaries, also known as maps or hash tables in other languages, are collections that store key-value pairs. Each key is unique and points to a specific value.
Characteristics of Dictionaries
- Unique Key: Each value within a dictionary has a unique key.
- Ordering: Dictionaries in C# do not guarantee a specific order of items.
- High Efficiency: Retrieving values using the key is extremely fast.
- Type Flexibility: Both the key and the value can be of any type, from primitives to custom objects.
Common Methods and Properties
Add(key, value): Adds a new key-value pair.ContainsKey(key): Checks whether a specific key exists.ContainsValue(value): Checks whether a specific value exists.TryGetValue(key, out value): Tries to get a value based on the provided key.Clear(): Clears all items from the dictionary.Count: Returns the number of key-value pairs in the dictionary.
Working with Dictionaries in C#
using System;
using System.Collections.Generic;
namespace Base {
class Dictionaries {
public void Run() {
Dictionary<string, int> people = new Dictionary<string, int>() {
{ "Nelson Silva", 28 },
{ "Larissa Fernandes", 37 }
};
people.Add("Pedro Henrique", 52);
people.Add("Raquel Soares", 68);
people["Pedro Henrique"] = 100;
people.Remove("Larissa Fernandes");
Console.WriteLine($"Number of people: {people.Count}\n");
foreach (KeyValuePair<string, int> person in people) {
Console.WriteLine($"Name: {person.Key}");
Console.WriteLine($"Age: {person.Value}\n");
}
}
}
}
Practical Case: Storing Application Settings
Imagine you are developing an application and need to store user settings, such as volume, brightness, and preferred language. A dictionary would be perfect for this!
Dictionary<string, object> settings = new Dictionary<string, object>() {
{ "Volume", 80 },
{ "Brightness", 50 },
{ "Language", "EN" }
};
With this dictionary, you can easily retrieve and modify the settings as needed.
Conclusion
Dictionaries in C# are an extremely powerful and versatile tool. Whether for storing settings, relating data, or managing complex collections, dictionaries are an excellent choice. Get familiar with them and you will see the efficiency and clarity they can bring to your code.