In this tutorial, we'll explore the functionality and versatility of Generic Collections in C#. Generics allow you to define type-safe data structures, meaning that you can check for the data type at compile time, preventing common type mismatches.
By the end of this tutorial, you'll learn:
- What Generic Collections are and why they're useful
- How to use List
- Best practices for working with Generic Collections
Prerequisites: Basic knowledge of C# programming language is required.
Generic collections are classes provided by the .NET Framework to store, retrieve, and manipulate data in a type-safe manner. The most commonly used Generic Collections are List
List
List<int> numbers = new List<int>();
numbers.Add(1);
numbers.Add(2);
numbers.Add(3);
In this example, we create a list of integers and add three elements to it.
Let's explore how to use the List
List<int> numbers = new List<int> {1, 2, 3, 4, 5}; // Initialize the list with some numbers
numbers.Add(6); // Add an item to the end of the list
numbers.Insert(0, 0); // Insert an item at a specific position
foreach (int number in numbers) // Traverse the list
{
Console.WriteLine(number); // Output: 0, 1, 2, 3, 4, 5, 6
}
A Dictionary
Dictionary<string, int> ages = new Dictionary<string, int>(); // Create a new dictionary
ages.Add("John", 28); // Add a key-value pair
ages.Add("Jane", 30); // Add another key-value pair
foreach (KeyValuePair<string, int> entry in ages) // Traverse the dictionary
{
Console.WriteLine($"Name: {entry.Key}, Age: {entry.Value}"); // Output: Name: John, Age: 28 and Name: Jane, Age: 30
}
In this tutorial, we've learned about Generic Collections in C#, why they're useful, and how to use List
For further learning, consider reading Microsoft's official documentation on Generic Collections.
Solutions:
List<string> movies = new List<string> {"Inception", "The Dark Knight", "Interstellar"};
foreach (string movie in movies)
{
Console.WriteLine(movie);
}
Dictionary<string, string> grades = new Dictionary<string, string> {{"John", "A"}, {"Jane", "B"}};
foreach (KeyValuePair<string, string> entry in grades)
{
Console.WriteLine($"Name: {entry.Key}, Grade: {entry.Value}");
}
For further practice, consider creating and manipulating a Stack