An array in C# is a collection of variables that are of the same type and stored in contiguous memory locations. Arrays allow you to store multiple values in a single variable, which makes them useful for handling collections of data efficiently. Each item in the array is accessed using an index, starting from zero.
Arrays in C# are zero-indexed, meaning the first element of the array has an index of 0.
1. Declaring and Initializing Arrays
In C#, arrays can be declared and initialized in several ways:
Syntax:
type[] arrayName;
type: The data type of the array elements (e.g., int, string).
arrayName: The name of the array.
You can initialize an array either when you declare it, or later with values.
Examples:
1.1. Declaring and Initializing an Array with Values:
int[] numbers = { 1, 2, 3, 4, 5 };
In this case, an integer array numbers is declared and initialized with values 1 through 5.
1.2. Declaring an Array Without Initializing It:
int[] numbers = new int[5]; // Creates an array of 5 integers with default values (0)
Here, the array numbers is declared with a size of 5, but it is not initialized with values. All elements are automatically set to the default value for integers (0).
2. Accessing Array Elements
Each element in the array is accessed by its index, with the first element having an index of 0.
Example:
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
// Access array elements
Console.WriteLine("First element: " + numbers[0]); // Output: 10
Console.WriteLine("Third element: " + numbers[2]); // Output: 30
}
}
In this example:
numbers[0] accesses the first element (10).
numbers[2] accesses the third element (30).
3. Modifying Array Elements
You can modify an array element by assigning a new value to a specific index.
Example:
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
// Modify the second element (index 1)
numbers[1] = 25;
// Print the modified array
Console.WriteLine("Modified second element: " + numbers[1]); // Output: 25
}
}
In this example:
numbers[1] is modified to 25.
The new value of the second element is printed.
4. Iterating Through an Array
To perform operations on each element of an array, you often need to iterate through it. You can do this using a for loop, foreach loop, or other iteration methods.
Example: Using a for Loop:
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
// Iterate through the array using a for loop
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
In this example:
The for loop iterates through the array from index 0 to numbers.Length - 1.
Each element of the array is accessed and printed.
Example: Using a foreach Loop:
using System;
class Program
{
static void Main()
{
int[] numbers = { 10, 20, 30, 40, 50 };
// Iterate through the array using a foreach loop
foreach (int num in numbers)
{
Console.WriteLine(num);
}
}
}
Output:
10
20
30
40
50
In this example:
The foreach loop automatically iterates through each element in the numbers array.
5. Multidimensional Arrays
C# also supports multidimensional arrays, such as 2D arrays, which are useful for representing tables or matrices.
Example: Declaring and Initializing a 2D Array:
using System;
class Program
{
static void Main()
{
// Declare and initialize a 2D array
int[,] matrix =
{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Access and print elements in the 2D array
Console.WriteLine("Element at [0,0]: " + matrix[0, 0]); // Output: 1
Console.WriteLine("Element at [2,1]: " + matrix[2, 1]); // Output: 8
}
}
In this example:
matrix is a 2D array with 3 rows and 3 columns.
We access elements using two indices: matrix[row, column].
6. Jagged Arrays
In addition to multidimensional arrays, C# also supports jagged arrays, which are arrays of arrays. Each inner array can have a different length.
Example: Declaring and Initializing a Jagged Array:
using System;
class Program
{
static void Main()
{
// Declare and initialize a jagged array
int[][] jaggedArray =
{
new int[] { 1, 2, 3 },
new int[] { 4, 5 },
new int[] { 6, 7, 8, 9 }
};
// Access and print elements in the jagged array
Console.WriteLine("Element at [0,2]: " + jaggedArray[0][2]); // Output: 3
Console.WriteLine("Element at [1,1]: " + jaggedArray[1][1]); // Output: 5
}
}
In this example:
jaggedArray is an array of arrays, with each inner array having a different length.
We access elements using two indices: jaggedArray[row][column].
7. Common Array Methods
C# provides several built-in methods for working with arrays:
Array.Length: Returns the total number of elements in the array.
Array.Sort(): Sorts the elements of the array.
Array.Reverse(): Reverses the elements of the array.
Example: Sorting and Reversing an Array:
using System;
class Program
{
static void Main()
{
int[] numbers = { 5, 3, 8, 1, 2 };
// Sort the array
Array.Sort(numbers);
Console.WriteLine("Sorted array:");
foreach (int num in numbers)
{
Console.Write(num + " "); // Output: 1 2 3 5 8
}
// Reverse the array
Array.Reverse(numbers);
Console.WriteLine("\nReversed array:");
foreach (int num in numbers)
{
Console.Write(num + " "); // Output: 8 5 3 2 1
}
}
}
8. Best Practices
Bounds Checking: Always ensure that you are accessing valid indices in your array (i.e., 0 <= index < array.Length).
Array Size: When you know the size of the array in advance, you can specify it directly. Otherwise, use collections like List<T> if the size can change dynamically.
Use foreach for Read-Only Access: If you don't need to modify array elements, use a foreach loop for better readability and safety.