Swap two variables without using a temp variable if
int a=4;
int b=3;
I need to swap these variable and get output as a=3 and b=4 without using another variable in C#
Swap two variables without using a temp variable if
int a=4;
int b=3;
I need to swap these variable and get output as a=3 and b=4 without using another variable in C#
Use Interlocked.Exchange()
int a = 4;
int b = 3;
b = Interlocked.Exchange(ref a, b);
From MSDN:
Sets a 32-bit signed integer to a specified value as an atomic operation, and then returns the original value
EDIT: Regarding Esoteric's fine link above (thank-you), there's even a Interlocked.Exchange() for double
that may help there too.
use the following concept
int a=4 ;
int b=3 ;
a=a+b ; // a=7
b=a-b ; // b=7-3=4
a=a-b ; // c=7-4=3
There are actually a couple of ways.
The following is considered an obfuscated swap.
a ^= b;
b ^= a;
a ^= b;
a = a + b;
b = a - b;
a = a - b;
Works the same with any language.
Using addition and subtraction
a = a + b;
b = a - b;
a = a - b;
Using xor operator
a = a ^ b;
b = a ^ b;
a = a ^ b;