While researching decompiled C# 7 libraries, one may encounter the use of ValueTuple generics. Understanding the purpose of ValueTuples and their advantages over traditional Tuples is crucial.
Key Differences:
Rationale for ValueTuples:
Introducing ValueTuples in C# 7 was driven by performance considerations:
Examples:
Demonstrating the usage and benefits of ValueTuples:
public (int sum, int count) DoStuff(IEnumerable<int> values) { var res = (sum: 0, count: 0); foreach (var value in values) { res.sum += value; res.count++; } return res; }
Using decomposing:
var result = DoStuff(Enumerable.Range(0, 10)); Console.WriteLine($"Sum: {result.sum}, Count: {result.count}");
Or using a fresh variable:
ValueTuple<int, int> valueTuple = DoStuff(Enumerable.Range(0, 10)); Console.WriteLine(string.Format("Sum: {0}, Count: {1})", valueTuple.Item1, valueTuple.Item2));
Compiler Implementation:
The compiler generates code that utilizes ValueTuple's fields internally, while providing named argument access for intuitive usage.
Conclusion:
ValueTuples offer significant performance and convenience advantages over traditional Tuples due to their value-type nature, mutability, and syntactic sugar.
The above is the detailed content of ValueTuple vs. Tuple in C#: What are the Key Performance and Design Differences?. For more information, please follow other related articles on the PHP Chinese website!