Arrays and ArrayLists in C# Programming
In C# programming, arrays and ArrayLists are used to store collections of data. While arrays are fixed in size, ArrayLists are dynamic and can grow or shrink as needed.
Arrays in C#
An array is a collection of elements of the same type. Arrays have a fixed size and are declared using square brackets.
Step-by-Step Example: Using Arrays
using System;
class Program {
static void Main() {
// Declare and initialize an array
int[] numbers = { 10, 20, 30, 40, 50 };
// Access elements
Console.WriteLine("First element: " + numbers[0]);
Console.WriteLine("Second element: " + numbers[1]);
// Iterate through the array
Console.WriteLine("All elements:");
for (int i = 0; i < numbers.Length; i++) {
Console.WriteLine(numbers[i]);
}
}
}
Output:
First element: 10
Second element: 20
All elements:
10
20
30
40
50
Key Points About Arrays
- Arrays are zero-indexed.
- They have a fixed size defined at the time of initialization.
- You can use the Length property to determine the number of elements.
ArrayLists in C#
An ArrayList is a dynamic collection that can hold elements of any type. It is part of the System.Collections namespace.
Step-by-Step Example: Using ArrayLists
using System;
using System.Collections;
class Program {
static void Main() {
// Create an ArrayList
ArrayList list = new ArrayList();
// Add elements
list.Add(10);
list.Add(20);
list.Add("Hello");
list.Add(40.5);
// Access elements
Console.WriteLine("First element: " + list[0]);
Console.WriteLine("Third element: " + list[2]);
// Iterate through the ArrayList
Console.WriteLine("All elements:");
foreach (var item in list) {
Console.WriteLine(item);
}
}
}
Output:
First element: 10
Third element: Hello
All elements:
10
20
Hello
40.5
Key Points About ArrayLists
- ArrayLists can store elements of different types.
- They are dynamic and can grow or shrink in size.
- Performance can be slower than arrays due to boxing and unboxing when working with value types.
Comparison of Arrays and ArrayLists
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type | Homogeneous | Can store mixed types |
| Performance | Faster | Slower due to boxing/unboxing |
Conclusion
Arrays and ArrayLists are essential data structures in C# for managing collections. Arrays are best for fixed-size, type-specific data, while ArrayLists provide flexibility with dynamic sizing and mixed types. Choose the one that best fits your application's needs.