# How to Swap Two Numbers in C# Without Using a Third Variable?

Recently, someone emailed our team asking, “How to write a c# program to swap two numbers without using third variable”? In this tutorial, I have explained how to swap two numbers in C# without using a third variable.

To swap two numbers in C# without using a third variable, you can either use arithmetic operations or bitwise XOR operations. In the arithmetic method, add the two numbers and assign the sum to the first variable, then subtract the second variable from the first and assign the result to the second variable, and finally subtract the second variable from the first again. In the bitwise XOR method, apply XOR to both numbers sequentially and assign the results back to the original variables.

## Swap Two Numbers in C# Without Using a Third Variable

In C#, swapping two numbers typically involves using a third variable as a temporary placeholder. However, there’s a more efficient way to do this – by using arithmetic or bitwise operations.

The concept behind this method is simple yet ingenious. We use addition and subtraction for arithmetic operations, while for bitwise operations, we use XOR (exclusive OR). Let’s delve into each method.

Method 1: Using Arithmetic Operations

Here’s the logic:

• Sum the two numbers and assign it to the first number.
• Subtract the second number from the new value of the first number and assign it to the second number.
• Again, subtract the second number from the first number to get the original value of the second number.

Method 2: Using Bitwise XOR Operation

The XOR operation is used in digital logic to compare bits. When swapping numbers:

• XOR the two numbers and assign it to the first number.
• XOR the second number with the new value of the first number and assign it to the second number.
• XOR the second number with the first number to get the original value of the second number.

Here is a complete code:

``````using System;

class Program
{
static void Main()
{
int num1 = 5, num2 = 10;

// Using Arithmetic Operations
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
Console.WriteLine(\$"After swapping (Arithmetic): num1 = {num1}, num2 = {num2}");

// Resetting values for the second example
num1 = 5; num2 = 10;

// Using Bitwise XOR
num1 = num1 ^ num2;
num2 = num1 ^ num2;
num1 = num1 ^ num2;
Console.WriteLine(\$"After swapping (Bitwise XOR): num1 = {num1}, num2 = {num2}");
}
}
``````

## Conclusion

Swapping two numbers without using a third variable in C# is an efficient technique that can save memory and processing time. In this tutorial, I have explained how to swap two numbers without using a third variable in C#.

You may like the following tutorials: