Arrays are one of the most fundamental data structures in C#. They allow you to store multiple values of the same data type in a single variable. Instead of creating many separate variables, you can group related values together and access them using an index.
For example, instead of writing:
string student1 = "Alice";
string student2 = "Bob";
string student3 = "Charlie";
You can write:
string[] students = { "Alice", "Bob", "Charlie" };
An array is a fixed-size collection. Once an array is created, its length cannot be changed. If you need a collection that grows or shrinks dynamically, consider using List<T> instead.
Arrays are zero-based, meaning the first element is stored at index
0, the second at index1, and so on.
Declaring an Array
An array declaration specifies the type of elements it will contain.
int[] numbers;
string[] names;
double[] prices;
At this point, only the variable has been declared. The array itself hasn’t been created yet.
Creating an Array
Use the new keyword to create an array and specify its size.
int[] numbers = new int[5];
This creates an array with five integer elements.
Because the array hasn’t been initialized with custom values, every element contains its default value.
Console.WriteLine(numbers[0]); // 0
Console.WriteLine(numbers[4]); // 0
Default values include:
| Data Type | Default Value |
|---|---|
int | 0 |
double | 0.0 |
bool | false |
char | '\0' |
Reference types (string, classes) | null |
Initializing an Array
Often you already know the values you want to store.
Using an array initializer
int[] numbers = { 10, 20, 30, 40, 50 };
Or equivalently:
int[] numbers = new int[]
{
10,
20,
30,
40,
50
};
With modern C# (C# 12), collection expressions can also be used:
int[] numbers = [10, 20, 30, 40, 50];
Accessing Array Elements
Each element is accessed using its index inside square brackets.
string[] fruits =
{
"Apple",
"Orange",
"Banana"
};
Console.WriteLine(fruits[0]);
Console.WriteLine(fruits[2]);
Output:
Apple
Banana
Remember:
- First element → index
0 - Second element → index
1 - Third element → index
2
Updating Array Elements
Array elements can be modified by assigning a new value to an index.
string[] colors =
{
"Red",
"Green",
"Blue"
};
colors[1] = "Yellow";
Console.WriteLine(colors[1]);
Output:
Yellow
Only the value changes. The size of the array remains the same.
Single-Dimensional Arrays
A single-dimensional array is the most common type of array. It stores elements in one continuous sequence.
int[] scores =
{
90,
85,
78,
95
};
You can access individual elements using one index.
Console.WriteLine(scores[0]);
Console.WriteLine(scores[3]);
Two-Dimensional Arrays
A two-dimensional array stores data in rows and columns, similar to a table or spreadsheet.
Declare a two-dimensional array:
int[,] matrix = new int[2, 3];
This creates:
2 rows
3 columns
You can also initialize it immediately.
int[,] matrix =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
The values are arranged like this:
1 2 3
4 5 6
Access an element using two indexes.
Console.WriteLine(matrix[0, 0]); // 1
Console.WriteLine(matrix[1, 2]); // 6
The first index represents the row, and the second represents the column.
Implicitly Typed Arrays
Sometimes the compiler can determine the array type automatically from the values provided.
Instead of writing:
int[] numbers = new int[]
{
1,
2,
3,
4
};
You can write:
var numbers = new[]
{
1,
2,
3,
4
};
The compiler infers that this is an int[].
Another example:
var cities = new[]
{
"London",
"Paris",
"Tokyo"
};
The compiler infers a string[].
All elements must be compatible with the same inferred type.
Array Length
Every array has a Length property that returns the total number of elements.
int[] values =
{
10,
20,
30,
40
};
Console.WriteLine(values.Length);
Output:
4
The last valid index is always:
Length - 1
For example:
Length = 5
Indexes:
0
1
2
3
4
Looping Through an Array
A for loop commonly uses the Length property.
int[] numbers =
{
5,
10,
15,
20
};
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
Using Length prevents accessing indexes that do not exist.
Can You Remove Items from an Array?
A common question is whether an element can be removed from an array.
The answer is no.
Arrays have a fixed size. After an array is created, its length cannot change.
For example, if an array contains five elements:
int[] numbers =
{
10,
20,
30,
40,
50
};
There is no method like:
numbers.Remove(30);
If you need to “remove” an item, you have a few options:
- Replace the value with another value.
- Create a new array with the desired elements.
- Use
List<T>instead of an array if items need to be added or removed frequently.
IndexOutOfRangeException
Attempting to access an index that doesn’t exist causes an IndexOutOfRangeException.
Example:
int[] numbers =
{
10,
20,
30
};
Console.WriteLine(numbers[3]);
This throws an exception because valid indexes are:
0
1
2
Similarly,
Console.WriteLine(numbers[-1]);
also throws an exception.
A good practice is to ensure the index is within the valid range before accessing the array.
int index = 2;
if (index >= 0 && index < numbers.Length)
{
Console.WriteLine(numbers[index]);
}
Using the Length property helps avoid this common programming error.
Summary
Arrays provide an efficient way to store multiple values of the same type in a fixed-size collection. They support direct access through zero-based indexes, making element retrieval very fast. You can create single-dimensional arrays for sequences of values or two-dimensional arrays for table-like data. Arrays can be initialized when they are created, and the compiler can even infer the element type for implicitly typed arrays.
Although the contents of an array can be updated, its size cannot change after creation. For scenarios that require adding or removing items dynamically, a List<T> is usually a better choice. Finally, always use the Length property when working with indexes to avoid IndexOutOfRangeException errors.
References: