Tuples can be very handy for developers

Touples return multiple values from a function, the creation of composite keys to Dictionaries and eliminates structs or classes just to fill combobox.

Basically, a tuple (Tuple in C#) is an ordered sequence, immutable, fixed-size and of heterogeneous objects, i.e., each object being of a specific type.


Examples:

Tuple<int, string, DateTime> _cliente = 
                Tuple.Create(1, "Kanha", new DateTime(1989, 12,24)); 

Tuples have a limit of 8 items. If you want to create a tuple with more items, we have to create nested Tuples.

To create a tuple with more than 8 items, we do as follows:

var t12 = new Tuple<int,int,int,int,int,int,int,Tuple<int,int,int,int, int>>
    (1, 2, 3, 4, 5, 6, 7, new Tuple<int,int,int, int,int>(8,9,10, 11, 12));
 <>var Item10 = t12.Rest.Item3;

So, Why Should We Use Them?

A) Return of Methods

Tuples provide a quick way to group multiple values into a single result, which can be very useful when used as a return of function, without the need to create parameters "ref" and / or "out ".

Example

using System;
namespace TuplesConsoleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var _cliente1 =RetornaCliente();
            
            Console.WriteLine("O Nome do usuário1 é: {0}", _cliente1.Item2);
            
            Console.Read();
        }
        static Tuple<int, string, DateTime> RetornaCliente()
        {
            Tuple<int, string, DateTime> _cliente = 
                        Tuple.Create(1, "Frederico", new DateTime(1975, 3, 24));
            return _cliente;
        }
    }
}

Conclusion

While the indiscriminated use of Tuples affects the readability of the code, its use at the appropriate time can be very handy for developers, allowing them to return multiple values from a function without the need to create parameters "ref" and / or "out", allowing the creation of composite keys to collections of type Dictionary and eliminates the need to create structs or classes or just to fill combobox or lists.


Comments