Arrays and Collections Explained
Key Concepts
In C#, arrays and collections are fundamental data structures used to store and manage groups of related data. Understanding how to use these structures effectively is crucial for writing efficient and organized code.
1. Arrays
An array is a fixed-size collection of elements of the same type. Each element in an array is accessed by its index, starting from 0. Arrays are useful when you know the exact number of elements you need to store and when the size of the collection is unlikely to change.
Example
int[] numbers = new int[5]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50; Console.WriteLine(numbers[2]); // Output: 30
2. Collections
Collections are dynamic data structures that can grow or shrink in size as needed. Unlike arrays, collections do not have a fixed size and can store elements of different types. C# provides several built-in collection classes, such as List<T>
, Dictionary<TKey, TValue>
, and Queue<T>
.
Example
List<string> names = new List<string>(); names.Add("Alice"); names.Add("Bob"); names.Add("Charlie"); Console.WriteLine(names[1]); // Output: Bob
3. List<T>
The List<T>
class is a dynamic array that can store elements of a specified type. It provides methods to add, remove, and access elements. The size of a List<T>
can change during the execution of the program.
Example
List<int> scores = new List<int> { 85, 90, 78, 92 }; scores.Add(88); scores.Remove(78); foreach (int score in scores) { Console.WriteLine(score); }
4. Dictionary<TKey, TValue>
The Dictionary<TKey, TValue>
class stores key-value pairs. Each key in the dictionary must be unique, and you can use the key to access its corresponding value. Dictionaries are useful when you need to store and retrieve data based on a unique identifier.
Example
Dictionary<string, int> ages = new Dictionary<string, int>(); ages.Add("Alice", 25); ages.Add("Bob", 30); ages.Add("Charlie", 35); Console.WriteLine(ages["Bob"]); // Output: 30
5. Queue<T>
The Queue<T>
class represents a first-in, first-out (FIFO) collection of objects. Elements are added to the end of the queue and removed from the beginning. Queues are useful for scenarios where you need to process items in the order they were added.
Example
Queue<string> tasks = new Queue<string>(); tasks.Enqueue("Task 1"); tasks.Enqueue("Task 2"); tasks.Enqueue("Task 3"); Console.WriteLine(tasks.Dequeue()); // Output: Task 1
Conclusion
Arrays and collections are essential tools in C# for managing groups of related data. Arrays are fixed-size and type-specific, while collections are dynamic and flexible. Understanding the differences and appropriate use cases for each will help you write more efficient and maintainable code.