C# 7.0 introduces a new tuple syntax that allows you to group multiple values together using a clean, lightweight syntax. Unlike the older Tuple<T1, T2>
class, these new tuples use value types for better performance and support named elements for improved readability.
Tuples are particularly useful for returning multiple values from methods without creating a dedicated class or struct, or for temporarily grouping related values.
Code
C#
(string name, int age) GetPerson()
{
return ("Alice", 30);
}
var person = GetPerson();
Console.WriteLine(person.name);
C#
Tuple<string, int> GetPerson()
{
return Tuple.Create("Alice", 30);
}
var person = GetPerson();
Console.WriteLine(person.Item1);
Notes
- You can either:
- Use named elements when declaring the tuple type
(string name, int age)
and access them by name - Use unnamed elements and access them by position
Item1
,Item2
, etc. - Infer names C# 7.1 from variable names when creating tuples
var tuple = (name, age);
- Use named elements when declaring the tuple type
- Tuples support deconstruction C# 7.0 allowing you to extract individual values directly
- Tuples are value types (specifically
ValueTuple<T1, T2, ...>
) unlike the older reference-typeTuple
class - Element names are compile-time only and don't exist at runtime, so reflection will only see
Item1
,Item2
, etc.