Home
C#
Swap Methods
Updated May 11, 2023
Dot Net Perls
Swap. A Swap method exchanges array element values. It acts on 2 separate elements so that they both are still present but in opposite locations.
In the C# language, there is no built-in method for this purpose on most types. You have to implement a custom swap method for string characters and other types.
This example shows how to swap two characters in a string's character buffer. It also shows how to swap two elements in an array with elements of type Int32.
int
Info For SwapCharacters, we use the ToCharArray method and the new string constructor and return a new string reference.
String Constructor
String ToCharArray
Note The string type is immutable and you cannot assign characters to locations in a string directly.
Next For SwapInts, the code uses a temporary variable, but the int array is modified in-place so no reference must be returned.
int Array
using System;

class Program
{
    static void Main()
    {
        // Swap characters in the string.
        string value1 = "abc";
        string swap1 = SwapCharacters(value1, 0, 1);
        Console.WriteLine(swap1);

        // Swap elements in array.
        int[] array1 = { 1, 2, 3, 4, 5 };
        SwapInts(array1, 0, 1);
        foreach (int element in array1)
        {
            Console.Write(element);
        }
        Console.WriteLine();
    }

    static string SwapCharacters(string value, int position1, int position2)
    {
        // Swaps characters in a string.
        char[] array = value.ToCharArray();
        char temp = array[position1];
        array[position1] = array[position2];
        array[position2] = temp;
        return new string(array);
    }

    static void SwapInts(int[] array, int position1, int position2)
    {
        // Swaps elements in an array.
        int temp = array[position1];
        array[position1] = array[position2];
        array[position2] = temp;
    }
}
bac
21345
Exceptions. This code will cause exceptions if you call it with invalid parameters. If needed, you can validate the arguments with if-statements and then throw.
if
Note This negatively impacts performance in tight loops—it is only necessary when many callers will exist.
ArgumentException
IndexOutOfRangeException
It is possible to develop methods that swap characters in a string or elements in an array. These methods were tested and proven correct on the input provided.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on May 11, 2023 (rewrite).
Home
Changes
© 2007-2025 Sam Allen