# Swapping the values of two variables

/// <summary>
/// Swapping the values of two variables by 3 different ways
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int a = 0;
int b = 1;
Swap1(ref a, ref b);
Console.WriteLine("a = {0}, b = {1}", a, b);

Swap2(ref a, ref b);
Console.WriteLine("a = {0}, b = {1}", a, b);

Swap3(ref a, ref b);
Console.WriteLine("a = {0}, b = {1}", a, b);

}

/// <summary>
/// With temp variable
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
private static void Swap1(ref int a, ref int b)
{
if (a != b)
{
int temp = a;
a = b;
b = temp;
}
}

/// <summary>
/// By subtraction
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
private static void  Swap2(ref int a, ref int b)
{
if (a != b)
{
a = a + b;
b = a – b;
a = a – b;
}
}

/// <summary>
/// XOR swap algorithm
///
/// a       0 1 0 1
/// b       0 0 1 1
/// result  0 1 1 0
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
private static void Swap3(ref int a, ref int b)
{
if (a != b)
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
}