Tuple data type in C #

Tram Ho

Why did I introduce Tuple?

While working, I have encountered many cases where the method we want to return a value, when arising or want to return more values, I have to create an object containing many of those values. return that object (ie I will have to change the type of data returned) and those cases only use that object once, such as maintaining a sourcecode of others and are afraid of changing it, use Tuple.

What is tuple?

Tuple introduced from .NET Framwork 4.0, is a structured data type that helps store complex data temporarily without having to create a new object class.

Each Tuple has predefined items1, item2, … There are a maximum of 8 items defined.

Each Tuple <> class has already been defined Property named Item1, Item2, Item3, … corresponding to the data types T1, T2, T3, … are transferred. The following image is an example:

Above kiows Tuple <T1, T2, T3, T4, T5, T6, T7, T8, TRest> when we transfer the data type, the map will correspond to the properties Item1, Item2, Item3, Item4, Item5 …

How to use Tuple?

Initializing a Tuple object has two ways:

  • Create via the Create method in the Tuple class:

  • Create via Constructor constructor:

Get the value from Tuple

Tuple cage

If you want to include more than eight elements in a tuple, you can do that by nesting another tuple object as the eighth element. The last nested data set can be accessed using the Rest property. To get values ​​from that nested tuple, use the Rest.Item1.Item <elelementNumber> command

You can place nested tuple objects anywhere in the string. However, nesting data sets should be placed at the end of the string to be accessible using the Rest attribute.

Tuple is used as a Method parameter

Tuples are used as a return type

Conclude.

You should use Tuple in the following situations:

  • When you want to return multiple values ​​from a method that do not want to use ref or out parameters
  • When you want to pass multiple values ​​to a method via a parameter
  • When you want to keep a database record or some temporary values ​​without creating a separate class

You should not use Tuple in the following situations:

  • Tuple is a reference data type, not a reference value. So improper use can affect the CPU
  • Tuple is limited to 8 elements. You need to use nested data sets if you need to store more elements. However, this can lead to confusion while working
  • In the process of getting data from tuple using attribute names such as Items1, Items2 does not look very clear. It will be difficult for the 2nd person to read into the code in the later process.

Wishing everyone a good job. ?

Reference article from source: https://docs.microsoft.com/en-us/dotnet/csharp/tuples

https://www.tutorialsteacher.com/csharp/csharp-tuple

Share the news now

Source : Viblo