System.Collections Code Samples

How do I swap two elements of an array?

The code below show you how to swap two elements of an array. The SwapElements() method use a temporary variable to keep the original value of the first element before swapping the elements.

In this example we use an extension method feature that available in C# 3.0 to add the swap capability for an array data type. In short, an extension method allow us to add new methods to the public contract of an existing CLR type without having to sub-class it or recompile to original type.

using System;

namespace Kodecsharp.Example.System.Collections
{
    public static class SwapArrayElementDemo
    {        
        public static void Main(string[] parameters)
        {
            int[] numbers = { 0, 1, 9, 2, 8, 3, 7, 4, 6, 5 };
            for (int i = 0; i < numbers.Length; i++)
            {
                Console.WriteLine("Numbers[" + i + "] = " + numbers[i]); 
            }

            numbers.SwapElements(2, 6);
            numbers.SwapElements(5, 0);

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

            string[] names = { "Alice", "Bob", "Carol", "Mallory" };
            foreach (string name in names)
            {
                Console.WriteLine("Name: " + name);
            }

            names.SwapElements(0, 3);

            foreach (string name in names)
            {
                Console.WriteLine("Name: " + name);
            }

            Console.ReadLine();
        }

        public static void SwapElements<T>(this T[] source, int from, int to)
        {
            T temp = source[from];
            source[from] = source[to];
            source[to] = temp;
        }
    }
}

If you run the example you will see the following result:

Numbers[0] = 0
Numbers[1] = 1
Numbers[2] = 9
Numbers[3] = 2
Numbers[4] = 8
Numbers[5] = 3
Numbers[6] = 7
Numbers[7] = 4
Numbers[8] = 6
Numbers[9] = 5
Numbers[0] = 3
Numbers[1] = 1
Numbers[2] = 7
Numbers[3] = 2
Numbers[4] = 8
Numbers[5] = 0
Numbers[6] = 9
Numbers[7] = 4
Numbers[8] = 6
Numbers[9] = 5
Name: Alice
Name: Bob
Name: Carol
Name: Mallory
Name: Mallory
Name: Bob
Name: Carol
Name: Alice