Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert a ValueTuple to a Tuple in C#
In C#, you can easily convert a ValueTuple to a Tuple using the ToTuple() method. ValueTuples are value types introduced in C# 7.0, while Tuples are reference types that have been available since earlier versions of C#.
Note − For .NET Framework projects, you may need to add the System.ValueTuple NuGet package to use ValueTuple features.
Syntax
Following is the syntax for converting a ValueTuple to a Tuple using the ToTuple() method −
var valueTuple = (value1, value2, value3); Tuple<T1, T2, T3> tuple = valueTuple.ToTuple();
Converting ValueTuple to Tuple
Example
using System;
class Program {
static void Main() {
// Create a ValueTuple
var valueTuple = (5, 50, 500, 5000);
Console.WriteLine("ValueTuple: " + valueTuple);
Console.WriteLine("ValueTuple Type: " + valueTuple.GetType().Name);
// Convert ValueTuple to Tuple
Tuple<int, int, int, int> tuple = valueTuple.ToTuple();
Console.WriteLine("Tuple: " + tuple);
Console.WriteLine("Tuple Type: " + tuple.GetType().Name);
}
}
The output of the above code is −
ValueTuple: (5, 50, 500, 5000) ValueTuple Type: ValueTuple`4 Tuple: (5, 50, 500, 5000) Tuple Type: Tuple`4
Converting Named ValueTuple to Tuple
Example
using System;
class Program {
static void Main() {
// Create a named ValueTuple
var employee = (Id: 101, Name: "John", Age: 30, Salary: 50000.0);
Console.WriteLine("Named ValueTuple: " + employee);
Console.WriteLine("Employee Name: " + employee.Name);
// Convert to Tuple (loses field names)
Tuple<int, string, int, double> empTuple = employee.ToTuple();
Console.WriteLine("Converted Tuple: " + empTuple);
Console.WriteLine("Employee Name from Tuple: " + empTuple.Item2);
}
}
The output of the above code is −
Named ValueTuple: (101, John, 30, 50000) Employee Name: John Converted Tuple: (101, John, 30, 50000) Employee Name from Tuple: John
Comparison
| Feature | ValueTuple | Tuple |
|---|---|---|
| Type | Value type (struct) | Reference type (class) |
| Memory | Stack allocated | Heap allocated |
| Named Fields | Supports named fields | Uses Item1, Item2, etc. |
| Mutability | Mutable | Immutable |
Installing System.ValueTuple Package
For .NET Framework projects (.NET 4.6.2 and earlier), you may need to install the System.ValueTuple NuGet package −
- Right-click on your project in Visual Studio Solution Explorer
- Select "Manage NuGet Packages"
- Click the "Browse" tab and search for "System.ValueTuple"
- Install the System.ValueTuple package by Microsoft
Conclusion
Converting ValueTuple to Tuple in C# is straightforward using the ToTuple() method. While ValueTuples offer better performance and named field support, Tuples remain useful for compatibility with older code that expects reference types.
