ValueTuples in C#

Introduction

Value Tuple is a tuple type introduced in C# 7.0. It is available for .Net Framework 4.7 and higher Versions.

If it is unavailable in your Project, you need to install the System.ValueTuple Package in your Project.

To install the NuGet Package, right-click on the Project and then select Manage NuGet Package from the options. This will open the NuGet Package Manager. Now click on Browse and search for System.ValueTuple and Select the System.ValueTuple Package.

When we talk about ValueTuple, a question comes to our mind- how is ValueTuple different from Tuple?

Differences between Tuple and ValueTuple in C#

  1. Tuple is a reference Type with Memory Allocation on the Heap, while ValueTuple is a value Type, as the name suggests, with Memory Allocation on Stack.
  2. Tuples can hold a maximum of 8 items; if we need to have more items, we need to use nested Tuples, but ValueTuple can hold over 8 items.
  3. Tuple comes into System.Tuple while ValueTuple is a part of the System.ValueTuple.
  4. ValueTuple allows us to have named Parameters, while with Tuple, there is no way to rename its items to describe the value for accessibility better.

ValueTuple in C#

ValueTuple is a mutable Struct that allows us to store a dataset with multiple values that may or may not be related.

It is easy to create and initialize the ValueTuple. It can be created and initialized using Parentheses () and specifying its values.

var student = (10, "Roshan", "Sharma");

It can also be initialized by specifying the Datatype of each element.

ValueTuple<int, string, string> student = (10, "Roshan", "Sharma");

student.Item1;  // returns 10
student.Item2;   // returns "Roshan"
student.Item3;   // returns "Sharma"

It can be declared another way as well.

(int, string, string) student = (10, "Roshan", "Sharma");

student.Item1;  // returns 10
student.Item2;   // returns "Roshan"
student.Item3;   // returns "Sharma"

A Tuple needs at least 2 values like the below.

(int, string) student = (10, "Roshan");

Named Fields

We can also assign Names to the ValueTuple Fields instead of having the default Fields, i.e., item1, item2, item3 so on.

(int Id, string FirstName, string LastName) student = (10, "Roshan", "Sharma");

person.Id;   // returns 10
person.FirstName;  // returns "Roshan"
person.LastName; // returns "Sharma"

ValueTuple in Methods

ValueTuple can be used in methods both as Parameters and return Type.

ValueTuple as Parameters

static void AddStudent((int, string, string) student)

{
              Console.WriteLine("{0}, {1}, {2}", student.Item1, student.Item2, student.Item3)
}

Value Tuple as Return Type

static (int, string, string) GetStudent(int student)

{
              return (10, "Roshan", "Sharma");
}

Conclusion

In this article, we learned about ValueTuples in C# and how they differ from tuples.


Similar Articles