System.ValueTuple vs. System.Tuple
What's the Difference?
System.ValueTuple and System.Tuple are two types that can be used to represent tuples in C#. However, there are several key differences between them.
Key Differences
Feature | ValueTuple | Tuple |
---|---|---|
Value type | Yes | No |
Mutability | Mutable | Immutable |
Item access | Fields | Properties |
Syntax sugar | Supports deconstruction and named arguments | Does not |
Performance | Allocation-free on the stack | Requires heap allocation |
ValueTuple
ValueTuple is a value type (struct), which means it is allocated on the stack and does not require garbage collection. It is a mutable struct, so its values can be changed after it has been created. ValueTuple exposes its items via fields instead of properties.
Tuple
Tuple is a reference type (class), which means it is allocated on the heap and requires garbage collection. It is an immutable class, so its values cannot be changed after it has been created. Tuple exposes its items via properties.
Why Use ValueTuple?
Using ValueTuple has several advantages over using Tuple:
Example
Using ValueTuple syntax:
public (int sum, int count) DoStuff(IEnumerable<int> values) { var result = (sum: 0, count: 0); foreach (var value in values) { result.sum += value; result.count++; } return result; }
Using deconstruction:
var (sum, count) = DoStuff(Enumerable.Range(0, 10)); Console.WriteLine($"Sum: {sum}, Count: {count}");
The above is the detailed content of ValueTuple vs. Tuple in C#: What are the Key Differences and When Should You Use Each?. For more information, please follow other related articles on the PHP Chinese website!