How to swap two numbers in C#
In this article, we will discuss how to swap two numbers in C#.
- we can swap two numeric values with temporary variable
- we can also use XOR(^) operator
- we can swap two numeric values with simple arithmetics
With temporary variable:
var temp = first;
first = second;
second = temp;
With XOR
first = first ^ second;
second = second ^ first;
first = first ^ second;
And as following
first = first + second;
second = first - second;
first = first - second;
You can find the code at my GitHub