C# Arrays

Arrays are fundamental data structures used to store collections of elements of the same type.

Introduction to Arrays

In C#, an array is a data structure that stores a fixed-size sequential collection of elements of the same type. The length of an array is determined when the array is created and cannot be changed afterwards. Arrays provide a way to group multiple variables of the same type under a single name, making it easier to manage related data.

Declaring and Initializing Arrays

You can declare an array by specifying the type of its elements followed by square brackets []. Initialization can be done in several ways:

1. Declaring and Instantiating an Array

You can declare an array variable, then create an instance of the array using the new keyword, specifying the type and size.

int[] numbers = new int[5];

This declares an array named numbers that can hold 5 integers. The elements are automatically initialized to their default values (0 for integers).

2. Declaring, Instantiating, and Initializing an Array

You can also initialize the array with values at the time of declaration using an initializer list.

string[] names = new string[3] { "Alice", "Bob", "Charlie" };

Alternatively, you can omit the size if you provide an initializer list:

double[] prices = { 19.99, 25.50, 10.00 };

Accessing Array Elements

Array elements are accessed using their zero-based index within square brackets. The index starts at 0 for the first element and goes up to length - 1 for the last element.

int[] scores = { 95, 88, 76, 92 };

// Accessing the first element
int firstScore = scores[0]; // firstScore will be 95

// Accessing the third element
int thirdScore = scores[2]; // thirdScore will be 76

// Modifying an element
scores[1] = 90; // The second element (index 1) is updated to 90
After modification, scores would be { 95, 90, 76, 92 }.

Array Properties and Methods

Arrays in C# have a Length property that returns the total number of elements in the array.

string[] fruits = { "Apple", "Banana", "Orange" };
int numberOfFruits = fruits.Length; // numberOfFruits will be 3
Console.WriteLine($"The array contains {numberOfFruits} fruits.");
Output: The array contains 3 fruits.

The System.Array class provides many static methods for working with arrays, such as sorting, searching, and copying.

Sorting an Array

The Array.Sort() method sorts the elements of an array in ascending order.

int[] unsortedNumbers = { 5, 2, 8, 1, 9 };
Array.Sort(unsortedNumbers);
// unsortedNumbers is now { 1, 2, 5, 8, 9 }

Iterating Through an Array

You can use a for loop or a foreach loop to iterate through the elements of an array.

Using a for loop:

int[] values = { 10, 20, 30 };
for (int i = 0; i < values.Length; i++)
{
    Console.WriteLine($"Element at index {i}: {values[i]}");
}
Output: Element at index 0: 10 Element at index 1: 20 Element at index 2: 30

Using a foreach loop:

string[] colors = { "Red", "Green", "Blue" };
foreach (string color in colors)
{
    Console.WriteLine(color);
}
Output: Red Green Blue

Multidimensional Arrays

C# supports multidimensional arrays, including 2D (rectangular) and jagged arrays.

Rectangular Arrays

Rectangular arrays have a fixed size for each dimension.

int[,] matrix = new int[3, 4]; // A 3x4 matrix

// Initializing and accessing elements
matrix[0, 1] = 5;
int value = matrix[0, 1]; // value will be 5

Jagged Arrays

Jagged arrays are arrays of arrays, where each inner array can have a different length.

int[][] jaggedArray = new int[3][]; // An array of 3 inner arrays

// Initializing inner arrays
jaggedArray[0] = new int[] { 1, 2 };
jaggedArray[1] = new int[] { 3, 4, 5 };
jaggedArray[2] = new int[] { 6 };

// Accessing an element
int element = jaggedArray[1][2]; // element will be 5
When choosing between rectangular and jagged arrays, consider the structure of your data. Rectangular arrays are simpler for fixed-size grids, while jagged arrays offer more flexibility when the size of sub-collections varies.

Common Array Operations

Arrays are a foundational concept in C# programming and are extensively used in various applications. Mastering arrays will significantly enhance your ability to handle collections of data efficiently.

For more advanced array operations and collections, explore the System.Collections.Generic namespace, which provides powerful types like List<T>, Dictionary<TKey, TValue>, and more.