Tip #013
Tuples and deconstruction
About this tip
Return a named tuple, then deconstruct it into variables. No class or out parameters. Need two values back from a method? It is available since C# 7. The key line is var (min, max) = MinMax(data) in tuples.cs. Run it and the output reads Min: 4, Range: 4..42.
Learn more
Did this tip save you some time? Consider buying me a coffee to fuel the next one.
Buy me a coffeeCode
int[] data = [4, 8, 15, 16, 23, 42];
var stats = MinMax(data);Console.WriteLine($"Min: {stats.Min}");
var (min, max) = MinMax(data);Console.WriteLine($"Range: {min}..{max}");
static (int Min, int Max) MinMax(int[] xs) => (xs.Min(), xs.Max());Output
$ dotnet run tuples.csMin: 4Range: 4..42