Swap Methods
This page was last reviewed on 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, uint
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.
Note This negatively impacts performance in tight loops—it is only necessary when many callers will exist.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 11, 2023 (rewrite).
© 2007-2024 Sam Allen.