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]; // Initialization

Example 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 / MethodDescriptionExample
LengthNumber of elements in the arraynumbers.Length
RankNumber of dimensionsnumbers.Rank
Clone()Creates a copy of the arrayint[] copy = (int[])numbers.Clone();
Array.Sort()Sorts the arrayArray.Sort(numbers);
Array.Reverse()Reverses the arrayArray.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]); // 6

Jagged 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

FeatureDescription
Declarationint[] arr;
Initializationarr = new int[5]; or int[] arr = {1,2,3};
Accessarr[index]
Lengtharr.Length
Multidimensionalint[,] matrix
Jagged Arraysint[][] jagged
Iterationfor or foreach

βœ… Tip:

  • Use arrays when size is fixed and elements are of the same type

  • For dynamic collections, consider List instead of arrays