Originally published at https://allcoderthings.com/en/article/csharp-arrays
In C#, arrays are used to store multiple values of the same type consecutively in memory. Indexing provides fast access to elements. This article provides a detailed introduction from array declarations to multi-dimensional arrays, as well as practical examples using Array class methods.
What is an Array?
An array is a structure where data of the same type is stored in consecutive memory cells. Each element is accessed using an index number. Indexes start at 0.
int[] numbers = new int[5]; // an int array with 5 elements
Declaring Arrays and Default Values
When declaring an array, its size is specified. If no values are assigned, default values are used:
-
int→ 0 -
bool→ false -
string→ null
string[] names = new string[3];
Console.WriteLine(names[0]); // null
Assigning and Accessing Array Elements (Indexing)
Elements are accessed by index. Since indexes start at 0, the last element is located at Length - 1.
int[] grades = new int[5];
grades[0] = 85;
grades[1] = 90;
grades[2] = 70;
grades[3] = 75;
grades[4] = 60;
Console.WriteLine(grades[1]); // 90
Console.WriteLine(grades[^1]); // 60, This will give last element (Length - 1)
int[] sub_grades = grades[1..4]; // A sub array: 90, 70, 75
grades[5] = 100; // This will throw IndexOutOfRangeException
Assigning or accessing indices outside the array size throws an
IndexOutOfRangeException. For example, inarray[4], valid indices are 0, 1, 2, 3. Values like -1, 4, or 5 will cause an error. The first element is always accessed with index 0.
Array Initialization Shortcuts
You can assign values directly while creating an array.
int[] numbers = { 10, 20, 30 };
var letters = new char[] { 'A', 'B', 'C' };
Iterating Over Arrays with Loops
for and foreach loops are used to access array elements.
int[] numbers = { 3, 6, 9 };
// with for
for (int i = 0; i < numbers.Length; i++)
Console.WriteLine(numbers[i]);
// with foreach
foreach (var n in numbers)
Console.WriteLine(n);
Multi-Dimensional Arrays (2D, 3D)
Multi-dimensional arrays are used to store data in table or matrix form. Elements can be accessed using indexes or iterated with nested loops.
int[,] matrix = new int[2, 3]
{
{1, 2, 3},
{4, 5, 6}
};
Console.WriteLine(matrix[1, 2]); // 6
// Iterating with nested for loops
for (int i = 0; i < matrix.GetLength(0); i++) // rows
{
for (int j = 0; j < matrix.GetLength(1); j++) // columns
{
Console.Write(matrix[i, j] + " ");
}
Console.WriteLine();
}
// Output:
6
1 2 3
4 5 6
Jagged Arrays
In jagged arrays, each row can have a different length. This is different from matrices.
int[][] jagged = new int[3][];
jagged[0] = new int[] {1, 2};
jagged[1] = new int[] {3, 4, 5};
jagged[2] = new int[] {6};
Console.WriteLine(jagged[1][2]); // 5
The Array Class and Useful Methods
In C#, all arrays derive from the Array class. Commonly used methods include:
int[] numbers = { 5, 2, 9, 1, 7 };
Array.Sort(numbers); // Sorting
Array.Reverse(numbers); // Reversing
int index = Array.IndexOf(numbers, 9); // Searching for element
Console.WriteLine(index);
Sample Application: Student Grades
In the following example, students' grades are stored in an array and their average is calculated.
int[] grades = { 80, 70, 95, 60, 100 };
int total = 0;
foreach (var g in grades)
total += g;
double average = (double)total / grades.Length;
Console.WriteLine($"Average: {average}");
TL;DR
- Arrays store values of the same type consecutively in memory.
- Indexes start at 0; default values are the type's default.
- You can iterate through arrays with
forandforeach.- Multi-dimensional and jagged arrays are supported.
- The
Arrayclass provides useful array methods.
Top comments (0)