---
title: "Swap variables elegantly in C#"
description: "How to swap variables elegantly in C#"
canonical_url: "https://nelsonbn.com/blog/csharp-swap-variables/"
---

> Index of every page on this site: [llms.txt](https://nelsonbn.com/llms.txt)

# Swap variables elegantly in C#

## Approach

### Classic way

```csharp
var a = 10;
var b = 20;

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

[Check here the resulted IL](https://sharplab.io/#v2:C4LglgNgPgAgTARgLACgYGYAE9MGFMDeqmJ2WMALJgLIAUAlIcaSwG4CGATpu5gLyYEABgDczFiQ7cARv0xxR4iUpa12AGkzTGA2tM3t6YlCwC+qU0A=)

### With tuple

```csharp
var a = 10;
var b = 20;

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

[Check here the resulted IL](https://sharplab.io/#v2:C4LglgNgPgAgTARgLACgYGYAE9MGFMDeqmJ2WMALJgLIAUAlIcaSwG4CGATpu5gLyYEABgDczFiQ7cARv0xxR4iUrZceAVwAec9mJQTSvAdL0GSsgey2nSAX1S2gA===)

## Benchmark

### For primitive types

![SwapPrimitivesBenchmarks](https://github.com/NelsonBN/doc-csharp-swap-variables/raw/main/media/SwapPrimitivesBenchmarks.png)

### For classes

![SwapClassesBenchmarks](https://github.com/NelsonBN/doc-csharp-swap-variables/raw/main/media/SwapClassesBenchmarks.png)

## 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

- [Tuple types (C# reference)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples)
- [Deconstructing tuples and other types](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/functional/deconstruct)

## Sitemap

See the full [sitemap](https://nelsonbn.com/sitemap.md) for all pages.
