Table of Contents
How to Create C# Tuples?
1. Using Constructor
Single Element Tuple
Multiple Element Tuple
2. Create Method
ValueTuple
How does Tuple Work?
Conclusion

C# Tuples

Sep 03, 2024 pm 03:30 PM
c# c# tutorial

The C# tuples is a data structure that was introduced in the C#.net version 4.0. The tuple data structure is designed to hold elements that are of different data types. Tuples help in returning multiple values from a class method in a single parameter which has many advantages over Out Parameters, class or structs types, or dynamic return type. As the parameters are passed into a single data set, it becomes easy to access this data set and perform different operations on it.

How to Create C# Tuples?

Tuples can be created in two different ways

1. Using Constructor

The constructor for creating the tuple is present in Tuple class. The acronym ‘T’ represents multiple datatype that are specified while creating the tuple. The elements stored in tuple are numbered zero to seven, that is any normal tuple holds only 8 elements and if one tries to enter more than 8 elements, compiler throws an error.

Single Element Tuple
Tuple <T1> (T1)
Copy after login

Example:

Tuple<int> Tuple_example = new Tuple<int>(27);
Console.WriteLine(Tuple_example);
Console.ReadLine();
Copy after login

Output:

C# Tuples

Multiple Element Tuple
Tuple <T1, T2> (T1, T2)
Copy after login

Example:

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "cat", true);
Console.WriteLine(tuple.Item1);
Console.WriteLine(tuple.Item2.ToString());
Console.ReadLine();
Copy after login

Output:

C# Tuples

2. Create Method

C# provides a static Create method to create tuple as follows

Single Element Tuple
Create (T1);
Copy after login

Example:

var Tuple_example = Tuple.Create(27);
Console.WriteLine(Tuple_example);
Console.ReadLine();
Copy after login

Output:

C# Tuples

Multiple Element Tuple
Create (T1, T2);
Copy after login

Example:

var Tuple_example = Tuple.Create(1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();
Copy after login
Copy after login

Output:

C# Tuples

While using the constructor, we need to specify the data type of every element while creating the tuple. The Create methods helps us in eliminating the cumbersome coding as shown above.

ValueTuple

The generic tuple is a reference type it means the values are stored on heap, which makes its usage costly in terms of memory and performance. C#7.0 introduced a new and improved version of Tuple over generic tuple and named it as ValueTuple. The ValueTuple is stored on the heap, which is easy to retrieve. The value tuple comes with .NET Framework 4.7 or .NET library 2.0. To separately install the tuple functionality, you need to install the NuGet Package called System.Value.Tuple.

Important points about ValueTuple

  • It is easy to create a ValueTuple

Example:

var Tuple_example = (1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();
Copy after login

Output:

C# Tuples

This is equivalent to:

var Tuple_example = Tuple.Create(1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();
Copy after login
Copy after login
  • The ValueTuple can also be declared without using the ‘var’ keyword. In this case we need to provide the datatype of each member

Example:

(int, string, bool) Tuple_example = (1, "cat", true);
Console.WriteLine(Tuple_example.Item1);
Console.WriteLine(Tuple_example.Item2.ToString());
Console.ReadLine();
Copy after login

Output:

C# Tuples

  • The values can be returned from a ValueTuple using

Example:

details.Item1;   – returns 28
details.Item2; -- returns ”CBC”
Copy after login
  • The ValueTuple, unlike the normal tuple, cannot contain only one element.

Example:

var detail = (28);  --this is not a tuple
var details = (28, “CBC”); -- this is a tuple
Copy after login

In the first statement, the compiler will not consider ‘detail’ as a tuple, instead, it will be considered and a normal ‘var’ type.

  • The ValueTuple can hold more than eight values without having to nest another tuple in the seventh position.
  • The properties in the ValueTuple can have different names than Item1, Item2 etc.
(int ID, String Firstname, string SecondName) details = (28, “CBC”, “C# Tuples”);
Copy after login
  • The elements in the ValueTuples can also be separated or discarded, depending on the need of the programming. In the above example, the element ‘FirstName’ can be discarded and a tuple containg first element and third element can be passed as a return type of the method.

How does Tuple Work?

  1. The C# framework allows only eight elements in the tuple, that means we can have values from 0 to 7 and if you want to create a Tuple with more than that, then specify the seventh element TRest as the nested tuple
var nestedtuple_example = new Tuple <int, string, string, int, int, int, string, Tuple<double, int, string>> (5, “This”, “is”, 7,8,9, “number”, Tuple.Create (17.33, 29,”April”));
Copy after login
  1. The one important use of tuple is to pass it as a single entity to the method without using the traditional ‘out’ and ‘ref’ keywords. The use of ‘Out’ and ‘ref’ parameters can be difficult and confusing, also the ‘out’ and ‘ref’ parameters do not work with ‘asnyc’ methods. e.g. public void TupleExampleMethod (Tuple tupleexample)
{
Var multiplication = tupleexample.Item1 * tupleexample.Item2;
Console.WriteLine (“Multiplication is”, {0}, multiplication);
}
Copy after login

The to the method TupleExampleMethod would look like

TupleExampleMethod(new Tuple<int, int> (34,56));
Copy after login
  1. The dynamic keyword can also be used to return values from any method, but it is seldom used due to performance issues. The returning of the tuple from a method.
public static Tuple <int, string> GetPerson()
{
return Tuple.Create (1, “abc”);
}
Copy after login

Let’s create a program in Visual to understand how tuple works.

  • Launch Visual Studio and create a windows project.

C# Tuples

  • We are creating a simple multiplication program that shows passing tuples by a method. A sample window created as below.

C# Tuples

The values from both textboxes are taken into a tuple and the tuple is passed on to a method.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnMultiply_Click(object sender, EventArgs e)
{
int value1 = Convert.ToInt32(txtVal1.Text);
int value2 = Convert.ToInt32(TxtVal2.Text);
CallMethod(new Tuple<int, int>(value1, value2));
}
private void CallMethod(Tuple<int, int> tuple)
{
txtResult.Text = Convert.ToString(tuple.Item1 * tuple.Item2);
Console.ReadLine();
}
}
}
Copy after login

The result is displayed in the third text box named as txtResult. End result looks like.

C# Tuples

Conclusion

The tuple data structure is a reference type, which means the values are stored on the heap instead of stack. This makes usage of tuples and accessing them in the program an intensive CPU task. The only 8 elements in tuples property is one of the major drawbacks of tuples as nested tuples are more prone to induce ambiguity. Also accessing elements in tuple with Item is also ambiguous as one must remember what position the element is on in order to access it. C#7 has introduced ValueTuple which is value type representation of tuple. It works only on .NET Framework 4.7 and hence needs to install separately from the Nuget package System.ValueTuple package.

The above is the detailed content of C# Tuples. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Active Directory with C# Active Directory with C# Sep 03, 2024 pm 03:33 PM

Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Random Number Generator in C# Random Number Generator in C# Sep 03, 2024 pm 03:34 PM

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

C# Serialization C# Serialization Sep 03, 2024 pm 03:30 PM

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

C# Data Grid View C# Data Grid View Sep 03, 2024 pm 03:32 PM

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Patterns in C# Patterns in C# Sep 03, 2024 pm 03:33 PM

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Prime Numbers in C# Prime Numbers in C# Sep 03, 2024 pm 03:35 PM

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Factorial in C# Factorial in C# Sep 03, 2024 pm 03:34 PM

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous c# The difference between multithreading and asynchronous c# Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

See all articles