Paramclasses Academy - Blog

Tutorials Details

←
Post 9 of 30
→

Wha is C# Arrays and Multidimensional Arrays with Practical Examples ?

Wha is C# Arrays and Multidimensional Arrays with Practical Examples ?

October 24, 2026

Introduction

Arrays are one of the fundamental concepts in C# programming. They allow developers to store multiple values of the same data type in a single variable instead of creating separate variables for every value.

For example, suppose you want to store the marks of five students. Creating five individual variables can make your program unnecessarily complicated. An array allows you to store all five marks together and process them efficiently using loops.

C# supports several array forms, including:

  • Single-dimensional arrays

  • Multidimensional arrays

  • Two-dimensional arrays

  • Jagged arrays

In this tutorial, you will learn how to declare, initialize, access, update, and iterate through arrays using practical examples.

1. What Is an Array in C#?

An array is a data structure that stores a fixed number of elements of the same type. Each element is accessed using an integer index.

For example:

int[] marks = { 85, 90, 78, 92, 88 };

This array stores five integer values in a single variable named marks.

The key characteristics of an array are:

  • All elements have the same element type.

  • Array elements are accessed by index.

  • Indexing starts at 0.

  • An array's length is fixed after the array is created.

  • Arrays are reference types in C#.

2. Declaring an Array in C#

To declare an array, specify the element type followed by square brackets.

Syntax

dataType[] arrayName;

Examples:

int[] numbers;
string[] names;
double[] prices;
bool[] statuses;
char[] letters;

These statements declare array variables. Before accessing elements, you must assign an initialized array to the variable.

Creating an Array with a Specific Size

int[] numbers = new int[5];

This creates an integer array containing five elements.

For a newly created int array, the elements initially contain 0.

You can assign values later:

numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;

Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[4]);

Output:

10
50

Remember that the first element is at index 0, while the last element is at index Length - 1.

3. Initializing an Array

C# provides several ways to initialize an array.

Method 1: Initialize with Values

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

The compiler determines the array length from the number of values.

Method 2: Use the new Keyword

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

This explicitly creates an array and initializes its elements.

Method 3: Specify the Size

int[] numbers = new int[5];

You can assign values individually after creating the array.

Method 4: Initialize a String Array

string[] fruits =
{
    "Apple",
    "Banana",
    "Mango",
    "Orange"
};

Console.WriteLine(fruits[2]);

Output:

Mango

The index 2 refers to the third element.

4. Accessing and Updating Array Elements

Array elements can be read or updated using their index.

Example

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

Console.WriteLine(numbers[0]);
Console.WriteLine(numbers[2]);

numbers[2] = 100;

Console.WriteLine(numbers[2]);

Output:

10
30
100

The statement numbers[2] = 100 replaces the value at index 2.

Important: Array Index Out of Range

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

Console.WriteLine(numbers[3]);

This throws an IndexOutOfRangeException because the valid indexes are 0, 1, and 2.

To avoid this error, ensure the index is within the valid range.

int index = 2;

if (index >= 0 && index < numbers.Length)
{
    Console.WriteLine(numbers[index]);
}

5. The Length Property

The Length property returns the total number of elements in an array.

Example

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

Console.WriteLine($"Array Length: {numbers.Length}");

Output:

Array Length: 5

The Length property is particularly useful in loops because it lets you process arrays without hardcoding their size.

Using Length with a for Loop

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

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

Output:

10
20
30
40
50

Using i < numbers.Length ensures that the loop stops before attempting to access an invalid index.

6. Iterating Through an Array Using foreach

The foreach loop provides a simple way to access every element without managing an index.

Example

string[] languages =
{
    "C#",
    "Java",
    "Python",
    "JavaScript"
};

foreach (string language in languages)
{
    Console.WriteLine(language);
}

Output:

C#
Java
Python
JavaScript

for vs foreach

Feature for foreach
Direct index access Yes No, not by default
Manual counter Usually required Not required
Simple collection traversal Suitable Often more readable
Convenient index-based updates Yes Generally use another approach

Use for when you need an index or want to update elements by position. Use foreach when you simply need to process each element.

7. Common Operations on Single-Dimensional Arrays

Arrays can be used for calculations, searching, and finding the largest or smallest value.

Example 1: Calculate the Sum

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

foreach (int number in numbers)
{
    sum += number;
}

Console.WriteLine($"Sum = {sum}");

Output:

Sum = 150

Example 2: Calculate the Average

int[] marks = { 80, 75, 90, 85, 70 };
int total = 0;

foreach (int mark in marks)
{
    total += mark;
}

double average = (double)total / marks.Length;

Console.WriteLine($"Average = {average:F2}");

Output:

Average = 80.00

Casting the total to double allows the average to include a fractional part when necessary.

Example 3: Find the Largest Number

int[] numbers = { 45, 12, 89, 34, 67 };

int largest = numbers[0];

foreach (int number in numbers)
{
    if (number > largest)
    {
        largest = number;
    }
}

Console.WriteLine($"Largest = {largest}");

Output:

Largest = 89

This example assumes the array contains at least one element.

Example 4: Find the Smallest Number

int[] numbers = { 45, 12, 89, 34, 67 };

int smallest = numbers[0];

foreach (int number in numbers)
{
    if (number < smallest)
    {
        smallest = number;
    }
}

Console.WriteLine($"Smallest = {smallest}");

Output:

Smallest = 12

Example 5: Search for a Number

int[] numbers = { 10, 20, 30, 40, 50 };
int target = 30;
bool found = false;

foreach (int number in numbers)
{
    if (number == target)
    {
        found = true;
        break;
    }
}

if (found)
{
    Console.WriteLine("Number found.");
}
else
{
    Console.WriteLine("Number not found.");
}

Output:

Number found.

The break statement stops the search once the target is found.

8. Sorting and Reversing Arrays

The Array class provides useful methods for common array operations.

Sorting an Array

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

Array.Sort(numbers);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

10
20
30
40
50

Array.Sort() sorts the array in ascending order for this integer example.

Reversing an Array

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

Array.Reverse(numbers);

foreach (int number in numbers)
{
    Console.WriteLine(number);
}

Output:

50
40
30
20
10

Array.Reverse() reverses the current order of elements. It does not automatically sort the values in descending order.

To obtain descending order, sort first and then reverse:

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

Array.Sort(numbers);
Array.Reverse(numbers);

9. What Is a Multidimensional Array?

A multidimensional array stores data across two or more dimensions.

For example, a two-dimensional array can represent rows and columns in a table, a classroom seating plan, or a matrix.

C# supports rectangular multidimensional arrays, such as:

int[,] matrix = new int[2, 3];

This creates an array with two rows and three columns.

The two indexes identify the row and column of an element.

10. Two-Dimensional Arrays in C#

Declaring a Two-Dimensional Array

int[,] numbers = new int[3, 3];

This creates three rows and three columns.

Initializing a Two-Dimensional Array

int[,] matrix =
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

The array represents the following matrix:

1 2 3
4 5 6
7 8 9

Accessing Elements

Console.WriteLine(matrix[0, 0]);
Console.WriteLine(matrix[1, 2]);
Console.WriteLine(matrix[2, 1]);

Output:

1
6
8

The first index identifies the row, and the second identifies the column. Both indexes start at 0.

Updating an Element

matrix[1, 1] = 100;

Console.WriteLine(matrix[1, 1]);

Output:

100

This replaces the element in the second row and second column.

11. Iterating Through a Two-Dimensional Array

Nested loops are commonly used to process rows and columns.

Example

int[,] matrix =
{
    { 1, 2, 3 },
    { 4, 5, 6 },
    { 7, 8, 9 }
};

for (int row = 0; row < matrix.GetLength(0); row++)
{
    for (int column = 0;
         column < matrix.GetLength(1);
         column++)
    {
        Console.Write($"{matrix[row, column]} ");
    }

    Console.WriteLine();
}

Output:

1 2 3
4 5 6
7 8 9

The GetLength() method returns the size of a particular dimension:

  • matrix.GetLength(0) returns the number of rows.

  • matrix.GetLength(1) returns the number of columns.

This approach works even when the array dimensions change.

12. Practical Example: Student Marks Table

Suppose a school stores the marks of three students across three subjects. A two-dimensional array can represent this information.

Program

int[,] marks =
{
    { 80, 85, 90 },
    { 75, 70, 88 },
    { 92, 89, 95 }
};

for (int student = 0;
     student < marks.GetLength(0);
     student++)
{
    int total = 0;

    for (int subject = 0;
         subject < marks.GetLength(1);
         subject++)
    {
        total += marks[student, subject];
    }

    double average = (double)total / marks.GetLength(1);

    Console.WriteLine(
        $"Student {student + 1}: Total = {total}, Average = {average:F2}");
}

Output:

Student 1: Total = 255, Average = 85.00
Student 2: Total = 233, Average = 77.67
Student 3: Total = 276, Average = 92.00

The outer loop processes students, while the inner loop calculates the total for each student's subjects.

This structure is useful for marks tables, sales reports, and other row-and-column datasets.

13. Three-Dimensional Arrays in C#

C# also supports arrays with three dimensions.

Example

int[,,] data = new int[2, 2, 2]
{
    {
        { 1, 2 },
        { 3, 4 }
    },
    {
        { 5, 6 },
        { 7, 8 }
    }
};

Console.WriteLine(data[0, 0, 0]);
Console.WriteLine(data[1, 1, 1]);

Output:

1
8

The three indexes identify positions along three dimensions.

Three-dimensional arrays can represent layered grids or other fixed-size multidimensional data. In everyday applications, however, a class-based model or collections may be easier to maintain when the data structure is complex.

14. What Is a Jagged Array?

A jagged array is an array whose elements are themselves arrays. Each inner array can have a different length.

Unlike a rectangular two-dimensional array, a jagged array does not require every row to contain the same number of elements.

Example

int[][] numbers = new int[3][];

numbers[0] = new int[] { 10, 20 };
numbers[1] = new int[] { 30, 40, 50 };
numbers[2] = new int[] { 60 };

foreach (int[] row in numbers)
{
    foreach (int number in row)
    {
        Console.Write($"{number} ");
    }

    Console.WriteLine();
}

Output:

10 20
30 40 50
60

Rectangular vs Jagged Arrays

Feature Rectangular Array Jagged Array
Example declaration int[,] int[][]
Structure Rows and columns in one rectangular array An array containing separate arrays
Row lengths Equal Can differ
Access example matrix[0, 1] numbers[0][1]
Suitable for Matrices and grids Rows with varying lengths

Use a rectangular array when the data naturally forms a regular grid. Use a jagged array when each row needs a different number of elements.

15. Useful Array Properties and Methods

C# provides several useful properties and methods for working with arrays.

Property or Method Purpose
Length Returns the total number of elements
Rank Returns the number of dimensions
GetLength(dimension) Returns the size of a specified dimension
Array.Sort() Sorts array elements
Array.Reverse() Reverses element order
Array.IndexOf() Returns the first matching index, or -1 if not found
Array.Copy() Copies elements into another array
Array.Clear() Resets a specified range to default values

Example: IndexOf

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

int index = Array.IndexOf(numbers, 30);

Console.WriteLine(index);

Output:

2

Example: Rank

int[,] matrix = new int[3, 4];

Console.WriteLine(matrix.Rank);
Console.WriteLine(matrix.Length);

Output:

2
12

The array has two dimensions and twelve total elements.

16. Arrays vs Lists in C#

Arrays are useful when the number of elements is known and fixed. A List<T> is more suitable when the collection needs to grow or shrink dynamically.

Feature Array List<T>
Size Fixed after creation Can grow or shrink
Index-based access Yes Yes
Element type Usually one specified type One specified generic type
Built-in add operation No automatic resizing Add()
Common use Fixed-size data Dynamic collections

Array Example

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

Console.WriteLine(numbers.Length);

List Example

List<int> numbers = new List<int>();

numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
numbers.Add(40);

Console.WriteLine(numbers.Count);

Output:

4

The List<T> type is part of System.Collections.Generic. In modern .NET projects, implicit usings may make an explicit using directive unnecessary; otherwise, include using System.Collections.Generic;.

17. Common Mistakes When Using Arrays

Mistake 1: Accessing an Invalid Index

An array with five elements has indexes from 0 to 4. Accessing index 5 causes an IndexOutOfRangeException.

Solution: Use Length or GetLength() to check valid bounds.

Mistake 2: Forgetting That Arrays Have Fixed Length

You cannot increase the length of an existing array. If you need a different size, create another array or use a collection such as List<T>.

Mistake 3: Confusing Length with the Last Index

For an array with five elements:

  • Length is 5.

  • The last valid index is 4.

Mistake 4: Using the Wrong Dimensions

For a two-dimensional array, use two indexes:

matrix[row, column]

For a jagged array, use separate indexing operations:

numbers[row][column]

Mistake 5: Assuming an Array Contains Elements

An array reference can be null if it has not been initialized. Accessing its members in that state causes a NullReferenceException.

Before using an array, ensure it has been assigned a valid array instance.

18. Best Practices for Working with Arrays

  • Use descriptive variable names such as studentMarks or productPrices.

  • Use Length instead of hardcoding the number of elements.

  • Use GetLength() for multidimensional array bounds.

  • Check indexes before performing potentially unsafe access.

  • Use foreach for simple traversal and for when you need indexes.

  • Choose rectangular or jagged arrays according to the structure of your data.

  • Use List<T> when the number of elements needs to change dynamically.

  • Keep array-processing logic readable and avoid unnecessary nested loops.

  • Consider what should happen when an array is empty before accessing its first element.

19. Practice Exercise

Create a C# console program to manage the marks of five students.

Requirements:

  1. Store five marks in an integer array.

  2. Print all marks using a loop.

  3. Calculate the total and average.

  4. Find the highest and lowest marks.

  5. Count how many students scored at least 40.

  6. Sort the marks in ascending order and display them.

Bonus Challenge: Create a two-dimensional array to store marks for five students across three subjects. Calculate each student's total and average.

Try to implement the solution independently before reviewing the examples again.

20. Frequently Asked Questions

Q1. What is an array in C#?

An array stores a fixed number of elements of the same type, accessed using indexes.

Q2. Why does array indexing start at zero?

C# uses zero-based indexing, meaning the first element is at index 0 and the last element is at index Length - 1.

Q3. What is a multidimensional array?

A multidimensional array stores elements across multiple dimensions, such as rows and columns in a two-dimensional matrix.

Q4. What is the difference between int[,] and int[][]?

int[,] is a rectangular two-dimensional array. int[][] is a jagged array containing separate arrays that may have different lengths.

Q5. Can an array's length change after creation?

No. An array's length is fixed after creation. To work with a dynamically growing collection, consider using List<T>.

Q6. What happens when you access an invalid array index?

C# throws an IndexOutOfRangeException when an array access uses an index outside the valid range.

Q7. Can arrays store strings and objects?

Yes. Arrays can store values of different element types through separate declarations, such as string[] for strings and object[] for object references and boxed values.

Q8. When should I use a multidimensional array?

Use a multidimensional array when the data naturally forms a regular grid, matrix, or table with fixed dimensions.

21. Quick Knowledge Check

Question 1: What is the index of the first element in a C# array?

A. -1

B. 0

C. 1

D. Length

Question 2: Which property returns the total number of array elements?

A. Count

B. Size

C. Length

D. Capacity

Question 3: Which declaration creates a rectangular two-dimensional integer array?

A. int[]

B. int[][]

C. int[,]

D. int[;]

Question 4: Which array type allows individual rows to have different lengths?

A. Single-dimensional array

B. Jagged array

C. Rectangular array

D. Fixed-length string

Answers: 1 — B, 2 — C, 3 — C, 4 — B.

Conclusion

Arrays are essential in C# because they allow related values to be stored and processed efficiently. Understanding single-dimensional arrays, multidimensional arrays, jagged arrays, indexes, and array methods gives you a strong foundation for working with data.

By combining arrays with loops and conditional statements, you can build practical programs for student marks, sales analysis, data processing, and many other real-world tasks.

Practice these examples, experiment with different array sizes, and learn when a fixed-size array is more appropriate than a dynamic collection.

←
Post 9 of 30
→