Mid Coding

Swap two numbers without using a temporary variable?

public void Swap(ref int a, ref int b) {

if (a != b) {

a ^= b;

b ^= a;

a ^= b;

Explanation:

XOR swap algorithm exchanges values without extra storage. (Check a != b to avoid

zeroing when both are same.)

More from C# Programming Tutorial

All questions for this course