Tuple in C#

Title

Tuple in C#

Introduction

A tuple is a finite ordered list of elements. In mathematics, an n-tuple is a sequence (or ordered list) of n elements, where n is a non-negative integer. There is only one 0-tuple, an empty sequence. An n-tuple is defined inductively using the construction of an ordered pair.

In C#, tuple is a generic static class that was added to C# 4.0 and it can hold any amount of elements, and they can be of any type we want. So using tuple, we can return multiple values. One great use of tuple might be returning multiple values from a method. It provides an alternative to “ref” or “out” if you have a method that needs return multiple new objects as part of its response.

A tuple allows you to combine multiple values of possibly different types into single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don’t want to create a new class.

We can create tuple using create method. This method provide us to create 8 overloads, so we can use a maximum of 8 data types cialis sans ordonnance with a tuple.
Following are the overloads

Create<T1>(T1) – 1-tuple or singleton

Create<T1,T2>(T1,T2) – 2-tuple or pair

Create<T1,T2,T3>(T1,T2,T3) – 3-tuple or triple

Create<T1,T2,T3,T4>(T1,T2,T3,T4) – 4-tuple or quadruple

Create<T1,T2,T3,T4,T5>(T1,T2,T3,T4,T5) – 5-tuple or quintuple

Create<T1,T2,T3,T4,T5,T6>(T1,T2,T3,T4,T5,T6) – 6-tuple or sextuple

Create<T1,T2,T3,T4,T5,T6,T7>(T1,T2,T3,T4,T5,T6,T7) – 7-tuple or septuple

Create<T1,T2,T3,T4,T5,T6,T7,T8>(T1,T2,T3,T4,T5,T6,T7,T8) – 8-tuple or octuplet

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //This represents tuple of size 2 (Create a new 2-tuple, or pair) with int &amp; string type
            var tuple1 = Tuple.Create&lt;string, int&gt;(&quot;Paras Babbar&quot;, 23);
            Console.WriteLine(&quot;Name is: &quot; + tuple1.Item1 + &quot; and age is: &quot; + tuple1.Item2);

            //This represents tuple of size 3 (Create a new 3-tuple, or triple) with int, string &amp; int type
            var tuple2 = Tuple.Create&lt;string&gt;(null);
        }
    }
}

OUTPUT

tuple

 


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar