C# Swap

Program data: rectangle

Swap exchanges array element values. It acts on two 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.

Tip:You have to implement a custom swap method for string characters and other types.

Example

Note

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. The method that swaps string characters is more complex.

StringsInt

Note:The string type is immutable and you cannot assign characters to locations in a string directly.

So:For the string swap method, we use the ToCharArray method and the new string constructor and return a new string reference.

String Constructor
C# program that swaps characters and array elements

using System;

class Program
{
    static void Main()
    {
	//
	// Swap characters in the string.
	//
	string value1 = "Dot Net Perls";
	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);
	}
    }

    static string SwapCharacters(string value, int position1, int position2)
    {
	//
	// Swaps characters in a string. Must copy the characters and reallocate the string.
	//
	char[] array = value.ToCharArray(); // Get characters
	char temp = array[position1]; // Get temporary copy of character
	array[position1] = array[position2]; // Assign element
	array[position2] = temp; // Assign element
	return new string(array); // Return string
    }

    static void SwapInts(int[] array, int position1, int position2)
    {
	//
	// Swaps elements in an array. Doesn't need to return a reference.
	//
	int temp = array[position1]; // Copy the first position's element
	array[position1] = array[position2]; // Assign to the second element
	array[position2] = temp; // Assign to the first element
    }
}

Output

oDt Net Perls       (The first two characters were swapped.)
21345               (The first two elements were swapped.)
Char type

The program defines two swap implementations. The SwapCharacters method receives three parameters: a reference to a string, and the first position and the second position of the values you want to swap.

SwapCharacters invokes the ToCharArray method, which returns the logical char buffer stored internally in the string. It uses a temporary variable, assigns the positions, and returns a new string.

ToCharArrayInt keyword

SwapInts returns no reference. It is a void method. It receives three parameters, the first being an array reference with elements of type Int32, and the two positions you want to exchange.

Also:It uses a temporary variable, but the int array is modified in-place so no reference must be returned.

Int ArrayWarning: exclamation mark

Exceptions. This code will cause exceptions if you call it with invalid parameters. If you are developing a library function that will have many callers, 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.

ArgumentNullExceptionIndexOutOfRangeException

XOR

XOR operator name

An interesting bitwise algorithm uses the XOR bitwise operator "^=" in the C# language to swap two elements. In computing history, this method was faster because it reduced the number of registers in use.

XOR

However:As Wikipedia notes it is now much slower than using a normal temporary variable.

XOR swap algorithm: Wikipedia

I have confirmed this in the C# language and the C programming language using GCC. In the C# language, bitwise operators are not the focus of the optimization efforts in the JIT. They thus may be neglected in optimization.

Summary

C# programming language

We saw methods that swap characters in a string or elements in an array. These methods were tested and proven correct on the input provided. We also discussed problems with swapping algorithms such as exceptions.

And:We noted the XOR swap algorithm and its drawbacks in modern programming languages and optimizing compilers.


C#: Method