What is an 'Array' in C#?
A foundational guide to arrays in C#. Learn how to use this fundamental data structure to store a fixed-size, sequential collection of elements of the same type.
In programming, a very common need is to store a collection of items. The most basic data structure for this in C# (and many other languages) is the array.
An array is a data structure that stores a fixed-size, sequential collection of elements of the same type. It's one of the most fundamental building blocks for storing data.
Declaring and Initializing an Array
You declare an array by specifying the type of its elements followed by square brackets []
.
// Declare an array of integers
int[] numbers;
To use the array, you must initialize it using the new
keyword, specifying its size. The size of an array cannot be changed after it is created.
// Initialize the array to hold 5 integers
numbers = new int[5];
You can also declare and initialize an array in a single line, providing the initial values in curly braces {}
. The compiler will automatically infer the size.
// Create and initialize an array of strings
string[] names = { "Alice", "Bob", "Charlie" };
Accessing Array Elements
Array elements are accessed by their index. C# uses zero-based indexing, so the first element is at index 0
, the second at index 1
, and so on.
string[] names = { "Alice", "Bob", "Charlie" };
// Access the first element
string firstName = names[0]; // "Alice"
// Modify the element at index 2
names[2] = "David";
If you try to access an index that is outside the bounds of the array (e.g., names[3]
in the example above), your program will throw an IndexOutOfRangeException
.
Getting the Length of an Array
The Length
property gives you the total number of elements that the array can hold.
int numberOfNames = names.Length; // 3
Iterating Through an Array
You can loop through the elements of an array using a for
loop or a foreach
loop.
Using a for
loop (useful if you need the index):
for (int i = 0; i < names.Length; i++)
{
Console.WriteLine($"Element at index {i}: {names[i]}");
}
Using a foreach
loop (simpler and more common):
foreach (var name in names)
{
Console.WriteLine(name);
}
Arrays vs. List<T>
C# provides another very common collection type, List<T>
. So when should you use an array?
- Arrays have a fixed size. Once you create an array of a certain size, you cannot add or remove elements to make it larger or smaller.
List<T>
has a dynamic size. You can freely add and remove items, and the list will grow and shrink accordingly.
Use an array when:
- You know exactly how many elements you need to store, and that number will not change.
- You are working with a performance-critical piece of code where the small overhead of a
List<T>
might matter.
Use a List<T>
when:
- You don't know how many elements you will need to store.
- You need to frequently add or remove elements.
- In almost all general-purpose scenarios, a
List<T>
is more flexible and easier to work with.
Multi-Dimensional Arrays
C# also supports multi-dimensional arrays, which are like a grid or a table.
// A 2D array (a 3x2 grid)
int[,] matrix = new int[3, 2];
// A 3D array
int[,,] cube = new int[3, 4, 5];
Conclusion
The array is a fundamental data structure in C#. It provides an efficient way to store a fixed-size collection of elements of the same type. While the more flexible List<T>
is often preferred for general-purpose use, understanding how arrays work is essential for any C# developer, as they are the foundation upon which many other collections are built.