Languages
[Edit]
EN

C# / .NET - swap method

11 points
Created by:
Root-ssh
175450

Swap operation in C#/.NET can be made in few ways.

1. Custom Swap method with reference arguments example

public static class SwapUtils
{
	public static void Swap<T>(ref T a, ref T b)
	{
		T tmp = a;

		a = b;
		b = tmp;
	}
}

Example:

int a1 = 3, b1 = 10;
int a2 = 4, b2 = 1;
int a3 = 5, b3 = 2;

SwapUtils.Swap(ref a1, ref b1);
SwapUtils.Swap(ref a2, ref b2);
SwapUtils.Swap(ref a3, ref b3);

Console.WriteLine("a1=" + a1 + ", b1=" + b1);
Console.WriteLine("a2=" + a2 + ", b2=" + b2);
Console.WriteLine("a3=" + a3 + ", b3=" + b3);

Output:

a1=10, b1=3
a2=1, b2=4
a3=2, b3=5

2. XOR swap algorithm example

int x = 3, y = 6;

x = x ^ y;
y = y ^ x;
x = x ^ y;

Console.WriteLine("x=" + x + ", y=" + y);
Note: this algorithm is useful with programming devices with very small amount of internal operating memory.

Output:

x=6, y=3

3. References

  1. ref keyword (C# Reference) - Microsoft Docs
  2. XOR swap algorithm - Wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join