Working with ValueTuple in C#

 

C# Examples

A tuple is a data structure introduced in C# 7.0 that consists of an ordered, finite series of immutable, heterogeneous fixed-size components. When developers declare that the items in a tuple are immutable, we indicate that they belong to a specific type that cannot be altered.

ValueTuple is a struct that represents a group of values. It can hold any number of types, but all the types must be value types. In C#, you use the ValueTuple class to create instances of ValueTuple.

In this C# programming tutorial, we will discuss the basics of ValueTuple, its differences from a tuple, benefits of a ValueTuple, and examples of how to write programs using ValueTuple in C#.

Want to learn C# in a class or online course environment? We have a list of the Best Online Courses to Learn C# to help you get started.

What is a ValueTuple in C#?

A ValueTuple is a struct that represents a lightweight, immutable pair of values. By default, it contains two elements – the first being an object and the second being of type System.ValueType, but programmers can specify their own types if required. It is also composable (meaning its parts can be combined with other tuples) and supports implicit conversions from any sequence that contains its constituent types.

A ValueTuple addresses two critical drawbacks of tuples: they are inefficient and must be referred to as Item1, Item2, and so on. That is, ValueTuples are both performant and referable by names chosen by the programmer.

Here are the key properties of a ValueTuple:

  • Value Tuples are mutable and not read-only
  • Value Tuples are structures and not classes
  • Data members of a Value Tuple (i.e., Item1, Item2, etc.) are fields and not properties

ValueTuple vs Tuple in C#

ValueTuple is a lightweight type for returning several values from a method. A ValueTuple is a value type with streamlined syntax and strict naming standards, as opposed to a tuple, which is a reference type. In addition, unlike a tuple, you can alter the fields in a ValueTuple.

One significant issue with the Tuple class is that it is a reference type allocated in the managed heap. Using it, developers might encounter CPU spikes and garbage collection pressure – (i.e., substantial performance concerns). The ValueTuple, on the other hand, is a lightweight value-type object with stack memory.

Consequently, a ValueTuple is much faster than a tuple in terms of performance. While the properties of a tuple are read-only, programmers cannot alter them after they have created the tuple; they can change the properties of a ValueTuple after they have created it.

Another difference between a tuple and a ValueTuple is that, while the former can hold only eight elements, a ValueTuple can contain more than eight elements.

Install the Required Package(s) for ValueTuple

To work with ValueTuple, developers should install the System.ValueTuple NuGet package onto their project either using the Package Manager or by executing the command given below at the .NET CLI:

dotnet add package System.ValueTuple

How to Create a ValueTuple in C#

Developers can create a ValueTuple in C# in one of the following ways:

  • By using the constructor
  • By using the Create method
  • By using parentheses

The following is the syntax for creating and initializing a ValueTuple in C#:

ValueTuple<data_type_1, data_type_2> tuple_name = (value_1, value_2);

To create a ValueTuple using the constructor, you can use the C# code below:

ValueTuple<int, string> valueTuple =
new ValueTuple<int, string>(1, "Hello World!");

To create a ValueTuple using the Create() method, you can use the following C# code:

var valueTuple = ValueTuple.Create(1, "Hello World!");

To create a ValueTuple using parentheses, you can use the following code:

(int Id, string text) valueTuple = (1, "Hello World!");

You can also convert a ValueTuple to a tuple. The following source code demonstrates how you can create a ValueTuple and then convert it to a tuple in C#:

var valueTuple = ValueTuple.Create(1, "Hello World!");
var tuple = valueTuple.ToTuple();

The source code below shows how programmers can create a ValueTuple containing three elements and then display the values of each of those elements at the console:

var employee = (1, "Joydip", "Kanjilal");
Console.WriteLine("Id: " + employee.Item1);
Console.WriteLine("First Name: " + employee.Item2);
Console.WriteLine("Last Name: " + employee.Item3);

Developers can also return a ValueTuple from a method in C#. The source code given below demonstrates how you can return a ValueTuple instance from a method in C#:

static (int, string) GetText()
{
    return (Id: 1, Text: "Hello World!");
}

You can use a ValueTuple as a parameter of a method. The following source code shows how this can be achieved:

static void DisplayText((int, string) text)
{
    Console.WriteLine("{0}, {1}", text.Item1, text.Item2);
}

Finally, coders can invoke the C# DisplayText method as shown here:

DisplayText((1, "Hello World!"));

Read: C# Tools for Code Quality

Using Named Properties with ValueType in C#

Developers can also create a ValueTuple with named members. The source code given below shows how you can create a ValueTuple having named members with C#:

(int Id, string Text) valueTuple = (1, "Hello World!");
Console.WriteLine("Id: {0}", valueTuple.Id);
Console.WriteLine("Text: {0}", valueTuple.Text);

Here is another example that illustrates how you can use named members in a ValueTuple:

var employee = (Id: 1, FirstName: "Joydip", LastName: "Kanjilal");
Console.WriteLine("Id: {0}" + employee.Id);
Console.WriteLine("First Name: {0}" + employee.FirstName);
Console.WriteLine("Last Name: {0}" + employee.LastName);

How to Use Deconstruct in C#

You can deconstruct a ValueTuple to retrieve the individual elements of it. For example, you can use deconstruction to retrieve the values of the properties of a ValueTuple. The source code given below shows how this can be achieved:

(int Id, string Text) = GetText();

Final Thoughts on ValueTuple in C#

ValueTuples have a simpler syntax and higher performance than tuples, as well as the ability to alter their data members and give them meaningful names. There are several advantages in using Value Tuples rather than tuples. However, support for ValueTuple is available only from C# 7.0 and .NET Framework 4.7.

Read more C# programming and software development tutorials.
.

Joydip Kanjilal
Joydip Kanjilal
A Microsoft Most Valuable Professional in ASP.NET, Speaker, and Author of several books and articles. More than 25 years of experience in IT with more than 18 years in Microsoft .NET and its related technologies. He was selected as a Community Credit Winner at http://www.community-credit.com several times. He has authored 8 books and more than 500 articles in some of the most reputed sites worldwide including MSDN, Info World, CodeMag, Tech Beacon, Tech Target, Developer, CodeGuru, and more.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read