Skip to main content

C# Arrays

Arrays are one of the fundamental data structures in C# that allow you to store multiple values of the same type in a single variable. Whether you're storing a list of numbers, names, or any collection of similar items, arrays provide a simple and efficient way to manage this data.

What is an Array?

An array in C# is a collection of elements of the same data type, stored at contiguous memory locations. Think of it as a container that can hold a fixed number of items where each item has a specific position (index).

Key characteristics of arrays in C#:

  • Fixed size (cannot change after creation)
  • Zero-indexed (positions start from 0)
  • Can be single or multi-dimensional
  • Store elements of the same data type

Creating Arrays

There are several ways to create arrays in C#:

1. Declaring and Initializing in One Step

csharp
// Declare and initialize with values
int[] numbers = { 1, 2, 3, 4, 5 };

// Declare and initialize a string array
string[] days = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

2. Declare First, Initialize Later

csharp
// Declare an array of integers with size 5
int[] scores = new int[5];

// Initialize individual elements
scores[0] = 85;
scores[1] = 92;
scores[2] = 78;
scores[3] = 95;
scores[4] = 88;

3. Alternative Syntax

csharp
// Another valid syntax
int[] points = new int[] { 10, 20, 30, 40, 50 };

Accessing Array Elements

To access elements in an array, use the index position inside square brackets:

csharp
int[] numbers = { 10, 20, 30, 40, 50 };

// Access an element
Console.WriteLine($"The first element is: {numbers[0]}"); // Output: The first element is: 10
Console.WriteLine($"The third element is: {numbers[2]}"); // Output: The third element is: 30

// Modify an element
numbers[1] = 25;
Console.WriteLine($"The updated second element is: {numbers[1]}"); // Output: The updated second element is: 25

Array Length

You can get the size of an array using the Length property:

csharp
int[] numbers = { 10, 20, 30, 40, 50 };
Console.WriteLine($"The array contains {numbers.Length} elements"); // Output: The array contains 5 elements

Iterating Through Arrays

There are several ways to iterate through an array:

Using a for loop

csharp
int[] scores = { 85, 92, 78, 95, 88 };

Console.WriteLine("Scores using for loop:");
for (int i = 0; i < scores.Length; i++)
{
Console.WriteLine($"Score {i+1}: {scores[i]}");
}

// Output:
// Scores using for loop:
// Score 1: 85
// Score 2: 92
// Score 3: 78
// Score 4: 95
// Score 5: 88

Using a foreach loop

csharp
string[] fruits = { "Apple", "Banana", "Cherry", "Date", "Elderberry" };

Console.WriteLine("Fruits using foreach loop:");
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}

// Output:
// Fruits using foreach loop:
// Apple
// Banana
// Cherry
// Date
// Elderberry

Multi-dimensional Arrays

C# supports multi-dimensional arrays, which can be either rectangular or jagged.

Rectangular Arrays (2D)

csharp
// Creating a 2D array (3 rows, 4 columns)
int[,] matrix = new int[3, 4] {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};

// Accessing elements
Console.WriteLine(matrix[1, 2]); // Output: 7 (row 1, column 2)

// Iterating through a 2D array
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1); j++)
{
Console.Write($"{matrix[i, j]}\t");
}
Console.WriteLine();
}

// Output:
// 1 2 3 4
// 5 6 7 8
// 9 10 11 12

Jagged Arrays (Arrays of Arrays)

csharp
// Declare a jagged array (array of arrays)
int[][] jaggedArray = new int[3][];

// Initialize the arrays
jaggedArray[0] = new int[] { 1, 2, 3 };
jaggedArray[1] = new int[] { 4, 5, 6, 7 };
jaggedArray[2] = new int[] { 8, 9 };

// Access elements
Console.WriteLine(jaggedArray[1][2]); // Output: 6

// Iterate through a jagged array
for (int i = 0; i < jaggedArray.Length; i++)
{
Console.Write($"Row {i}: ");
for (int j = 0; j < jaggedArray[i].Length; j++)
{
Console.Write($"{jaggedArray[i][j]} ");
}
Console.WriteLine();
}

// Output:
// Row 0: 1 2 3
// Row 1: 4 5 6 7
// Row 2: 8 9

Common Array Operations

Copying Arrays

csharp
int[] originalArray = { 1, 2, 3, 4, 5 };

// Method 1: Using Array.Copy
int[] copy1 = new int[originalArray.Length];
Array.Copy(originalArray, copy1, originalArray.Length);

// Method 2: Using Clone()
int[] copy2 = (int[])originalArray.Clone();

// Method 3: Using CopyTo()
int[] copy3 = new int[originalArray.Length];
originalArray.CopyTo(copy3, 0);

Sorting Arrays

csharp
int[] unsortedNumbers = { 5, 2, 8, 3, 1, 6 };

// Sort the array
Array.Sort(unsortedNumbers);

Console.WriteLine("Sorted array:");
foreach (int num in unsortedNumbers)
{
Console.Write($"{num} ");
}
// Output: Sorted array: 1 2 3 5 6 8

Searching in Arrays

csharp
int[] numbers = { 10, 20, 30, 40, 50 };

// Binary search (array must be sorted)
int index = Array.BinarySearch(numbers, 30);
Console.WriteLine($"30 found at index: {index}"); // Output: 30 found at index: 2

// Find the index of the first occurrence
int firstIndex = Array.IndexOf(numbers, 40);
Console.WriteLine($"First occurrence of 40 is at index: {firstIndex}"); // Output: First occurrence of 40 is at index: 3

// Check if array contains a value
bool contains = Array.Exists(numbers, element => element == 20);
Console.WriteLine($"Array contains 20: {contains}"); // Output: Array contains 20: True

Resizing Arrays

Since arrays have a fixed size, to "resize" an array, you actually create a new array and copy the elements:

csharp
int[] original = { 1, 2, 3 };

// Resize to a larger array
Array.Resize(ref original, 5);
original[3] = 4;
original[4] = 5;

Console.WriteLine("Resized array:");
foreach (int num in original)
{
Console.Write($"{num} ");
}
// Output: Resized array: 1 2 3 4 5

// Resize to a smaller array
Array.Resize(ref original, 2);
Console.WriteLine("\nTruncated array:");
foreach (int num in original)
{
Console.Write($"{num} ");
}
// Output: Truncated array: 1 2

Practical Examples

Example 1: Calculate Average Temperature

csharp
double[] weeklyTemperatures = { 72.5, 75.0, 68.3, 70.1, 74.2, 79.8, 76.5 };

// Calculate the average temperature
double sum = 0;
foreach (double temp in weeklyTemperatures)
{
sum += temp;
}
double average = sum / weeklyTemperatures.Length;

Console.WriteLine($"Average weekly temperature: {average:F1}°F");
// Output: Average weekly temperature: 73.8°F

Example 2: Student Grade Tracker

csharp
string[] studentNames = { "Alice", "Bob", "Charlie", "Diana", "Evan" };
int[] scores = { 92, 85, 78, 95, 88 };

// Display student grades
Console.WriteLine("Student Grades:");
for (int i = 0; i < studentNames.Length; i++)
{
string grade;
if (scores[i] >= 90) grade = "A";
else if (scores[i] >= 80) grade = "B";
else if (scores[i] >= 70) grade = "C";
else if (scores[i] >= 60) grade = "D";
else grade = "F";

Console.WriteLine($"{studentNames[i]}: {scores[i]} ({grade})");
}

// Find highest scorer
int highestScore = scores[0];
int highestIndex = 0;
for (int i = 1; i < scores.Length; i++)
{
if (scores[i] > highestScore)
{
highestScore = scores[i];
highestIndex = i;
}
}

Console.WriteLine($"\nHighest score: {studentNames[highestIndex]} with {highestScore}");

// Output:
// Student Grades:
// Alice: 92 (A)
// Bob: 85 (B)
// Charlie: 78 (C)
// Diana: 95 (A)
// Evan: 88 (B)
//
// Highest score: Diana with 95

Example 3: Basic Inventory System

csharp
// Product inventory example
string[] productNames = new string[5];
double[] prices = new double[5];
int[] quantities = new int[5];

// Initialize with some products
productNames[0] = "Laptop";
prices[0] = 1200.00;
quantities[0] = 5;

productNames[1] = "Monitor";
prices[1] = 350.00;
quantities[1] = 8;

productNames[2] = "Keyboard";
prices[2] = 80.00;
quantities[2] = 12;

// Display inventory
Console.WriteLine("Current Inventory:");
Console.WriteLine("--------------------------------");
Console.WriteLine("Product\tPrice\tQuantity\tValue");
Console.WriteLine("--------------------------------");

double totalValue = 0;
for (int i = 0; i < productNames.Length; i++)
{
if (productNames[i] != null)
{
double value = prices[i] * quantities[i];
totalValue += value;
Console.WriteLine($"{productNames[i]}\t${prices[i]}\t{quantities[i]}\t\t${value}");
}
}

Console.WriteLine("--------------------------------");
Console.WriteLine($"Total Inventory Value: ${totalValue}");

// Output:
// Current Inventory:
// --------------------------------
// Product Price Quantity Value
// --------------------------------
// Laptop $1200 5 $6000
// Monitor $350 8 $2800
// Keyboard $80 12 $960
// --------------------------------
// Total Inventory Value: $9760

Common Pitfalls and Best Practices

IndexOutOfRangeException

One of the most common exceptions when working with arrays is the IndexOutOfRangeException, which occurs when you try to access an index that doesn't exist:

csharp
int[] numbers = { 1, 2, 3 };
// This will throw an IndexOutOfRangeException:
// Console.WriteLine(numbers[3]); // Index 3 is out of range

Always ensure you're accessing valid indices by checking against the array's length.

Arrays vs. Other Collections

Arrays are great for fixed-size collections, but if you need a dynamic collection that can resize, consider using:

  • List<T> for a resizable array
  • Dictionary<TKey, TValue> for key-value pairs
  • Other specialized collections in the System.Collections.Generic namespace

Memory Considerations

Large arrays are allocated on the heap rather than the stack, which can impact performance for very large arrays.

Summary

Arrays in C# provide a powerful way to work with collections of data of the same type:

  • They have a fixed size defined when created
  • Elements are accessed by index (starting at 0)
  • Arrays can be single or multi-dimensional
  • Common operations include sorting, searching, and iterating
  • Arrays are perfect for fixed-size collections of data

Despite the emergence of more dynamic collection types, arrays remain fundamental in C# programming and understanding them thoroughly is essential for any C# developer.

Exercises

To strengthen your understanding of C# arrays, try these exercises:

  1. Write a program to find the second largest element in an array
  2. Create a program that merges two sorted arrays into a single sorted array
  3. Implement a program to remove duplicates from an array
  4. Write a program that rotates an array to the right by k steps
  5. Create a basic tic-tac-toe game using a 2D array to represent the board

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)