What is a tuple in C#, and when should you use one?
Quick Answer
A tuple bundles a few values into one lightweight object without declaring a type: (string name, int age) p = ("Sam", 30);. Modern C# uses ValueTuple — a mutable struct with named elements. Use it for a method returning two or three related values internally; use a named type (record/class) once it's part of a public API or gains behaviour.
A tuple lets me group a couple of values together on the fly without writing a class — I can return (bool found, decimal total) from a private method and the caller deconstructs it with var (found, total) = .... Modern C# gives you ValueTuple with the parentheses syntax and named elements; it's a struct, so no heap allocation. It's great for internal plumbing. The moment the shape becomes part of a public contract or needs methods and validation, I promote it to a record or a class with a real name.
- Deconstruction:
var (name, age) = GetPerson();. ValueTuple(parentheses syntax) is a value type; the olderSystem.Tupleis a reference type withItem1/Item2names only.- Tuples have structural equality — handy as a composite dictionary key.
- Don't leak tuples across module boundaries — the element names are just compiler sugar and get weak in metadata.