0
0
CsharpHow-ToBeginner · 3 min read

How to Reverse Array in C#: Simple Guide with Examples

In C#, you can reverse an array easily using the Array.Reverse() method, which modifies the array in place. Alternatively, you can create a new reversed array using LINQ with array.Reverse() for a non-destructive approach.
📐

Syntax

The primary way to reverse an array in C# is using the Array.Reverse() method. It takes the array as a parameter and reverses its elements in place.

  • Array.Reverse(array); reverses the entire array.
  • You can also reverse a part of the array by specifying a start index and length: Array.Reverse(array, startIndex, length);
csharp
Array.Reverse(array);

// Or to reverse part of the array
Array.Reverse(array, startIndex, length);
💻

Example

This example shows how to reverse an array of integers using Array.Reverse(). It prints the original array and the reversed array.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };
        Console.WriteLine("Original array: " + string.Join(", ", numbers));

        Array.Reverse(numbers);

        Console.WriteLine("Reversed array: " + string.Join(", ", numbers));
    }
}
Output
Original array: 1, 2, 3, 4, 5 Reversed array: 5, 4, 3, 2, 1
⚠️

Common Pitfalls

One common mistake is expecting Array.Reverse() to return a new reversed array. It actually reverses the original array in place and returns void. To keep the original array unchanged, use LINQ's Reverse() method which returns a new reversed sequence.

Also, be careful when reversing only part of the array; ensure the startIndex and length are within the array bounds to avoid exceptions.

csharp
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        // Wrong: This does not create a new reversed array
        // Array.Reverse(numbers) returns void
        // int[] reversed = Array.Reverse(numbers); // Compile error

        // Right: Use LINQ to create a new reversed array
        int[] reversed = numbers.Reverse().ToArray();

        Console.WriteLine("Original array: " + string.Join(", ", numbers));
        Console.WriteLine("New reversed array: " + string.Join(", ", reversed));
    }
}
Output
Original array: 1, 2, 3, 4, 5 New reversed array: 5, 4, 3, 2, 1
📊

Quick Reference

  • Reverse entire array: Array.Reverse(array);
  • Reverse part of array: Array.Reverse(array, startIndex, length);
  • Create new reversed array: var reversed = array.Reverse().ToArray(); (requires using System.Linq;)

Key Takeaways

Use Array.Reverse(array) to reverse an array in place in C#.
To keep the original array unchanged, use LINQ's Reverse() method and convert to an array.
Remember Array.Reverse() returns void and modifies the original array.
You can reverse only a part of the array by specifying start index and length.
Always check array bounds when reversing a subrange to avoid errors.