C#: Generic method for reversing an array

This entry is part 62 of 71 in the series C#

An array could be comprised of integer or string.

Here, we work out a method to reverse an array be it a string array or an integer array.

using System;

namespace ReverseArray
{
    public static class Extensions
    {
        public static void ReverseArray<T>(this T[] array)
        {
            array.ReverseArray(0, array.Length - 1);
        }

        public static void ReverseArray<T>(this T[] array, int lower, int upper)
        {
            for (int i = lower, j = upper; i < j; i++, j--)
            {
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int[] arr1 = { 1, 2, 3, 4, 5, 6, 7, 8 };
            arr1.ReverseArray();

            foreach (int i in arr1)
            {
                Console.Write("{0} ", i);
            }
            Console.WriteLine();

            int[] arr2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
            arr2.ReverseArray(2, 6);

            foreach (int n in arr2)
            {
                Console.Write("{0} ", n);
            }
            Console.WriteLine();

            string[] arr3 = { "The", "End", "Of", "The", "Innocent"};
            arr3.ReverseArray();

            foreach (string s in arr3)
            {
                Console.Write("{0} ", s);
            }

            Console.ReadKey();
        }
    }
}

genericarray

Series Navigation<< C#: Generic method
C#: Generic classes >>