Home > Backend Development > C++ > ValueTuple vs. Tuple in C#: What are the Key Differences and When Should You Use Each?

ValueTuple vs. Tuple in C#: What are the Key Differences and When Should You Use Each?

Susan Sarandon
Release: 2024-12-30 14:58:10
Original
704 people have browsed it

ValueTuple vs. Tuple in C#: What are the Key Differences and When Should You Use Each?

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:

  • Avoids allocation penalty due to being a value type
  • Provides automatic shallow equality semantics
  • Supports deconstruction and named arguments, which makes working with tuples more convenient and less ambiguous
  • Optimized equality implementation for better performance

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;
}
Copy after login

Using deconstruction:

var (sum, count) = DoStuff(Enumerable.Range(0, 10));
Console.WriteLine($"Sum: {sum}, Count: {count}");
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template