C# Tuples

WBOY
Release: 2024-09-03 15:30:55
Original
706 people have browsed it

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!

Related labels:
source:php
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!