Arrays in C# are powerful data structures that allow you to store multiple elements of the same type in a fixed-size, contiguous block of memory. They provide efficient access to elements using numeric indices.
To declare an array in C#, specify the type followed by square brackets and a variable name. Here's a simple example:
int[] numbers;
string[] names;
You can initialize arrays in several ways:
int[] numbers = new int[5]; // Creates an array of 5 integers
string[] fruits = new string[] { "apple", "banana", "orange" };
var colors = new[] { "red", "green", "blue" };
Array elements are accessed using zero-based indexing. The first element is at index 0, the second at index 1, and so on.
int[] scores = { 85, 92, 78, 95, 88 };
Console.WriteLine(scores[0]); // Outputs: 85
scores[2] = 80; // Modifies the third element
C# arrays come with useful properties and methods:
Length
: Returns the total number of elements in the array.Rank
: Returns the number of dimensions in the array.Sort()
: Sorts the elements in the array.Reverse()
: Reverses the order of elements in the array.C# supports multidimensional arrays. These are arrays of arrays, allowing you to create tables or matrices. For more information, check out the guide on C# Multidimensional Arrays.
Jagged arrays are arrays of arrays where each sub-array can have a different length. They offer more flexibility than regular multidimensional arrays. Learn more about them in our C# Jagged Arrays guide.
You can iterate through arrays using various loop constructs. The foreach loop is particularly useful for arrays:
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
Console.WriteLine(num);
}
IndexOutOfRangeException
.Array.Sort()
and Array.Find()
for common operations.Arrays are fundamental to C# programming, offering efficient storage and access to collections of data. Understanding how to declare, initialize, and manipulate arrays is crucial for effective C# development. As you progress, explore more advanced concepts like LINQ for powerful array operations.