C# 7.0 introduced tuples with named elements, but required you to explicitly specify the names when creating them. This led to redundant code when the variable names matched the desired tuple element names.
C# 7.1 improves this by automatically inferring tuple element names from the variables or properties used to create the tuple, eliminating the redundancy and making tuple creation more concise.
Code
C#
var name = "Alice";
var age = 30;
var person = (name, age);
Console.WriteLine(person.name); // Alice
Console.WriteLine(person.age); // 30
C#
var name = "Alice";
var age = 30;
var person = (name: name, age: age);
Console.WriteLine(person.name); // Alice
Console.WriteLine(person.age); // 30
Notes
- Inference works with variables, properties, and fields but not with method calls or complex expressions
- You can still explicitly name elements to override the inferred names
- If an element cannot be inferred (e.g., a literal or expression), it falls back to the default names
Item1
,Item2
, etc.