Letβs go through arrays in C# β a fundamental way to store multiple values of the same type.
π 1. What is an Array?
-
An array is a collection of elements of the same type stored in contiguous memory locations.
-
Each element is accessed by an index, starting at 0.
-
Fixed size (cannot grow/shrink dynamically).
π 2. Declaring and Initializing Arrays
Syntax
type[] arrayName; // Declaration
arrayName = new type[size]; // InitializationExample 1: Declare and Initialize Separately
int[] numbers; // Declaration
numbers = new int[5]; // Array of 5 integers
numbers[0] = 10;
numbers[1] = 20;Example 2: Declare and Initialize Together
int[] numbers = new int[5] { 1, 2, 3, 4, 5 };
string[] names = { "Alice", "Bob", "Charlie" }; // Implicit sizeπ 3. Accessing Array Elements
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine(numbers[0]); // 10
numbers[2] = 35; // Update element at index 2
Console.WriteLine(numbers[2]); // 35-
Index starts at 0
-
Last element =
length - 1
π 4. Array Properties & Methods
| Property / Method | Description | Example |
|---|---|---|
Length | Number of elements in the array | numbers.Length |
Rank | Number of dimensions | numbers.Rank |
Clone() | Creates a copy of the array | int[] copy = (int[])numbers.Clone(); |
Array.Sort() | Sorts the array | Array.Sort(numbers); |
Array.Reverse() | Reverses the array | Array.Reverse(numbers); |
π 5. Multidimensional Arrays
2D Array (Matrix)
int[,] matrix = new int[2,3] { {1,2,3}, {4,5,6} };
Console.WriteLine(matrix[1,2]); // 6Jagged Array (Array of Arrays)
int[][] jagged = new int[2][];
jagged[0] = new int[] {1, 2};
jagged[1] = new int[] {3, 4, 5};
Console.WriteLine(jagged[1][2]); // 5-
Multidimensional array β rectangular
-
Jagged array β each βrowβ can have different lengths
π 6. Iterating Through Arrays
int[] numbers = { 1, 2, 3, 4, 5 };
// Using for loop
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
// Using foreach loop
foreach (int num in numbers)
{
Console.WriteLine(num);
}-
forβ use index -
foreachβ simpler, read-only access
π 7. Summary Table
| Feature | Description |
|---|---|
| Declaration | int[] arr; |
| Initialization | arr = new int[5]; or int[] arr = {1,2,3}; |
| Access | arr[index] |
| Length | arr.Length |
| Multidimensional | int[,] matrix |
| Jagged Arrays | int[][] jagged |
| Iteration | for or foreach |
β Tip:
-
Use arrays when size is fixed and elements are of the same type
-
For dynamic collections, consider List instead of arrays