System.Collections Code Samples
Page 1 of 1 |
Prev
|
Next
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.
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