C# Tuples
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
Single Element Tuple
Tuple <T1> (T1)
Example:
Tuple<int> Tuple_example = new Tuple<int>(27); Console.WriteLine(Tuple_example); Console.ReadLine();
Output:
Multiple Element Tuple
Tuple <T1, T2> (T1, T2)
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();
Output:
2. Create Method
C# provides a static Create method to create tuple as follows
Single Element Tuple
Create (T1);
Example:
var Tuple_example = Tuple.Create(27); Console.WriteLine(Tuple_example); Console.ReadLine();
Output:
Multiple Element Tuple
Create (T1, T2);
Example:
var Tuple_example = Tuple.Create(1, "cat", true); Console.WriteLine(Tuple_example.Item1); Console.WriteLine(Tuple_example.Item2.ToString()); Console.ReadLine();
Output:
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();
Output:
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();
- 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();
Output:
- The values can be returned from a ValueTuple using
Example:
details.Item1; – returns 28 details.Item2; -- returns ”CBC”
- 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
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”);
- 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?
- 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”));
- 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); }
The to the method TupleExampleMethod would look like
TupleExampleMethod(new Tuple<int, int> (34,56));
- 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”); }
Let’s create a program in Visual to understand how tuple works.
- Launch Visual Studio and create a windows project.
- We are creating a simple multiplication program that shows passing tuples by a method. A sample window created as below.
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(); } } }
The result is displayed in the third text box named as txtResult. End result looks like.
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
The above is the detailed content of C# Tuples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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.

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.

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

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 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.
