Swap variables elegantly in C#

22 Oct, 2022
C#.NET

Swap variables elegantly in C#

Approach

Classic way

var a = 10;
var b = 20;

var aux = a;
a = b;
b = aux;

Check here the resulted IL

With tuple

var a = 10;
var b = 20;

(a, b) = (b, a);

Check here the resulted IL

Benchmark

For primitive types

SwapPrimitivesBenchmarks

For classes

SwapClassesBenchmarks

Conclusion

In both cases the performance difference is not measurable.

The only difference is that the tuple approach is more readable and less error prone. So, use it! 🤓

References

We are using cookies to ensure that we give you the best experience on our website. By clicking "Accept", you consent to the use of ALL the cookies. However you may visit Cookie policy to provide a controlled consent.