C# offers several ways to work with collections of data. While arrays provide efficient storage for a fixed number of elements, the List<T>
class offers dynamic resizing and greater flexibility. Understanding the strengths and weaknesses of each approach is crucial for writing efficient and maintainable C# code.
Table of Contents
Working with Arrays in C#
Arrays in C# are fixed-size data structures. Once declared, their size cannot be changed. This characteristic makes them memory-efficient when the number of elements is known beforehand. However, you can populate the array elements after declaration.
Here’s how to add values to an array using a for
loop:
// Declare an integer array of size 5
int[] numbers = new int[5];
// Add values using a for loop
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = i * 10; // Assign values: 0, 10, 20, 30, 40
}
// Print the array elements
Console.WriteLine("Array elements:");
foreach (int number in numbers)
{
Console.WriteLine(number);
}
Remember that attempting to access an index beyond the array’s bounds (e.g., numbers[5]
) will result in an IndexOutOfRangeException
.
Utilizing Lists for Dynamic Collections
The List<T>
class provides a dynamic, resizable alternative to arrays. Its size adjusts automatically as you add or remove elements, making it suitable when the final size is unknown.
Here’s how to add values to a List<T>
:
// Declare a list of integers
List<int> numbersList = new List<int>();
// Add values using List<T>.Add(T) method
numbersList.Add(15);
numbersList.Add(25);
numbersList.Add(35);
numbersList.Add(45);
numbersList.Add(55);
// Print the list elements
Console.WriteLine("nList elements:");
foreach (int number in numbersList)
{
Console.WriteLine(number);
}
//Convert List<T> to array if needed
int[] numbersArrayFromList = numbersList.ToArray();
Console.WriteLine("nArray created from List:");
foreach (int number in numbersArrayFromList)
{
Console.WriteLine(number);
}
The Add()
method efficiently appends elements. The ToArray()
method allows conversion back to an array if necessary.
Choosing the Right Approach
The best choice depends on your specific needs:
- Arrays: Ideal when the size is known in advance and performance is paramount. They offer better memory efficiency for fixed-size collections.
- Lists: Preferred when the size is unknown or elements need frequent addition or removal.
List<T>
provides flexibility, although performance might be slightly lower than arrays for a large number of sequential additions. This difference is often negligible unless dealing with extremely large datasets where performance is critical.