It’s easy to reverse the contents of an array using C# generics:

static T[] ReverseArray<T>( T[] array )
{
    T[] newArray = null;
    int count = array == null ? 0 : array.Length;
    if (count > 0)
    {
        newArray = new T[count];
        for (int i = 0, j = count - 1; i < count; i++, j--)
        {
            newArray[i] = array[j];
        }
    }
    return newArray;
}

And here is an example of how you might call this method:

int[] intArray =
    new int[] { 1, 2, 3, 4 };
int[] intArrayReversed =
    ReverseArray<int>( intArray );

string[] stringArray =
    new string[] { "A", "B", "C", "D" };
string[] stringArrayReversed =
    ReverseArray<string>( stringArray );

Note that this method should be used only when you want to create a NEW array. If you simply want to reverse an existing array in place, use the static Array.Reverse method.

Here is a console program to test this method:

using System;

namespace ReverseArray
{
    class Program
    {
        static void Main( string[] args )
        {
            TestReverse<int>( new int[0] );
            TestReverse<int>( new int[] { 1 } );
            TestReverse<int>( new int[] { 1, 2 } );
            TestReverse<int>( new int[] { 1, 2, 3 } );
            TestReverse<int>( new int[] { 1, 2, 3, 4 } );

            TestReverse<string>( null );
            TestReverse<string>( new string[] { "A" } );
            TestReverse<string>( new string[] { "A", "B" } );
            TestReverse<string>( new string[] { "A", "B", "C" } );
            TestReverse<string>( new string[] { "A", "B", "C", "D" } );

            Console.ReadLine();
        }
        static void TestReverse<T>( T[] array )
        {
            Write( array );
            array = ReverseArray<T>( array );
            Write( array );
            Console.WriteLine();
        }
        static void Write<T>( T[] array )
        {
            if (array != null)
            {
                foreach (T i in array)
                {
                    Console.Write( "{0} ", i );
                }
            }
            Console.WriteLine();
        }
        static T[] ReverseArray<T>( T[] array )
        {
            T[] newArray = null;
            int count = array == null ? 0 : array.Length;
            if (count > 0)
            {
                newArray = new T[count];
                for (int i = 0, j = count - 1; i < count; i++, j--)
                {
                    newArray[i] = array[j];
                }
            }
            return newArray;
        }
    }
}

Here is the program output:

1
1

1 2
2 1

1 2 3
3 2 1

1 2 3 4
4 3 2 1

A
A

A B
B A

A B C
C B A

A B C D
D C B A

Share and Enjoy:
  • Digg
  • Twitter
  • Facebook
  • Reddit
  • StumbleUpon
  • LinkedIn
  • Google Bookmarks
  • Slashdot