Working with Arrays in C#: A Comprehensive Guide to Array Handling

This tutorial provides a comprehensive guide to working with arrays in C#. It covers array declaration, initialization, accessing elements, common operations, and best practices for efficient array manipulation in C# programming.



Working with Arrays in C#

Understanding C# Arrays

In C#, an array is a data structure that stores a fixed-size sequence of elements of the same data type. Arrays are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on. Arrays are objects in C#, derived from the `System.Array` class. This means they have properties and methods you can use to work with them.

Advantages of Using Arrays

  • Code Optimization: Arrays are efficient for storing and accessing collections of data.
  • Random Access: You can access any element directly using its index.
  • Easy Traversal: Simple to iterate through all elements using loops.
  • Data Manipulation: Easy to sort, search, and modify array elements.

Disadvantages of Using Arrays

  • Fixed Size: The size of a C# array is set at the time of creation and cannot be easily changed (resizing requires creating a new, larger array and copying elements).

Types of C# Arrays

  • Single-Dimensional Arrays: Store elements in a single row (e.g., `int[] myArray = new int[5];` ).
  • Multi-Dimensional Arrays: Store elements in multiple dimensions (e.g., `int[,] myArray = new int[3, 4];` creates a 3x4 grid).
  • Jagged Arrays: Arrays of arrays, where each inner array can have a different length (e.g., `int[][] myJaggedArray = new int[3][];` ).

Creating and Using Single-Dimensional Arrays

Here are examples demonstrating array creation, initialization, and traversal. Note that uninitialized elements contain default values (0 for integers).

Example 1: Creating and Initializing an Array

C# Code

int[] numbers = new int[5]; // Creates an array of 5 integers
numbers[0] = 10;
numbers[2] = 20;
numbers[4] = 30;

Example 2: Declaration and Initialization Together

You can declare and initialize an array at the same time using several approaches.

C# Code

int[] numbers1 = new int[5] { 10, 20, 30, 40, 50 }; //Size specified
int[] numbers2 = new int[] { 10, 20, 30, 40, 50 }; //Size inferred
int[] numbers3 = { 10, 20, 30, 40, 50 }; //Size inferred, `new` omitted

Example 3: Traversing with a `for` Loop

C# Code

int[] numbers = { 10, 20, 30, 40, 50 };
for (int i = 0; i < numbers.Length; i++) {
    Console.WriteLine(numbers[i]);
}

Example 4: Traversing with a `foreach` Loop

C# Code

int[] numbers = { 10, 20, 30, 40, 50 };
foreach (int number in numbers) {
    Console.WriteLine(number);
}