Swapping Two Numbers in C# Without a Temporary Variable: Efficient Techniques

Learn two efficient methods for swapping two integer variables in C# without using a temporary variable. This tutorial explains these techniques using arithmetic operations (addition/subtraction, multiplication/division), compares their efficiency, and discusses potential limitations.



Swapping Two Numbers in C# Without a Temporary Variable

This article demonstrates two common techniques for swapping the values of two integer variables in C# without using a third, temporary variable. These methods utilize basic arithmetic operations.

Method 1: Using Multiplication and Division

This method uses multiplication and division to swap the values. It's concise but can be less efficient and might have limitations if dealing with numbers that could result in overflow or division by zero.


int a = 5, b = 10;
a = a * b; // a now holds the product
b = a / b; // b now holds the original value of a
a = a / b; // a now holds the original value of b

Method 2: Using Addition and Subtraction

This method is another concise approach that uses addition and subtraction to swap values. Similar to the multiplication/division method, it avoids the use of a temporary variable but might have limitations with very large numbers that can lead to an overflow.


int a = 5, b = 10;
a = a + b; // a now holds the sum
b = a - b; // b now holds the original value of a
a = a - b; // a now holds the original value of b