0
0
CsharpHow-ToBeginner · 3 min read

How to Use Array.Reverse in C# - Simple Guide

Use Array.Reverse(array) to reverse the order of elements in an array in C#. This method modifies the original array in place without returning a new array.
📐

Syntax

The Array.Reverse method reverses the order of elements in the specified array. It modifies the original array directly.

  • array: The array you want to reverse.
csharp
Array.Reverse(array);
💻

Example

This example shows how to reverse an integer array using Array.Reverse. It prints the array before and after reversing.

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

Modifies original array: Array.Reverse changes the original array and does not return a new one. If you need to keep the original, create a copy first.

Works only on arrays: This method works only on arrays, not on lists or other collections.

csharp
using System;

class Program
{
    static void Main()
    {
        int[] original = { 10, 20, 30 };

        // Wrong: expecting a new reversed array
        // int[] reversed = Array.Reverse(original); // This won't compile

        // Right: reverse original array in place
        Array.Reverse(original);
        Console.WriteLine(string.Join(", ", original));

        // To keep original, copy first
        int[] copy = (int[])original.Clone();
        Array.Reverse(copy);
        Console.WriteLine("Copy reversed: " + string.Join(", ", copy));
    }
}
Output
30, 20, 10 Copy reversed: 30, 20, 10
📊

Quick Reference

  • Array.Reverse(array): Reverses the entire array in place.
  • Array.Reverse(array, index, length): Reverses a portion of the array starting at index for length elements.

Key Takeaways

Array.Reverse reverses the elements of an array in place without returning a new array.
It works only on arrays, not on other collection types like lists.
To keep the original array unchanged, create a copy before reversing.
You can reverse the entire array or just a part of it using the overload with index and length.
Always remember that the original array is modified after calling Array.Reverse.