EDUDOTNET

Tuesday, October 8, 2013

What is a Tuple in C#? When it use? Example of Tuple

Tuple:

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 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 to return multiple new objects as part of its response.


A tuple allows you to combine multiple values of possibly different types into a 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 a Tuple using the Create method. This method provide to 8 overloads, so we can use a maximum of 8 data types with a Tuple. 


Followings are overloads: 


Create(T1)- Tuple of size 1
Create(T1,T2)- Tuple of size 2
Create(T1,T2,T3) – Tuple of size 3
Create(T1,T2,T3,T4) – Tuple of size 4
Create(T1,T2,T3,T4,T5) – Tuple of size 5
Create(T1,T2,T3,T4,T5,T6) – Tuple of size 6
Create(T1,T2,T3,T4,T5,T6,T7) – Tuple of size 7
Create(T1,T2,T3,T4,T5,T6,T7,T8) – Tuple of size 8

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
namespace EDUDOTNET_TupleDemo
{
    class EDUDOTNET
    {
        static void Main(string[] args)
        {
            //This represents a tuple of size 3 (Create a new 3-tuple, or Triple) with all string type
            var tuple = Tuple.Create<stringstringstring>("EDUDOTNET""IT""SOLUTION");
            Console.WriteLine(tuple); 
            //This represents a tuple of size 2 (Create a new 2-tuple, or Pair) with int & string type
            var tuple1 = Tuple.Create<intstring>(51, "CTO-EDUDOTNET");
            Console.WriteLine(tuple1);        
            
            //We can also access values of Tuple using ItemN property. Where N point to a particular item in the tuple.
            //This represents a tuple of size 4 (Create a new 4-tuple, or quadruple) with 3 string & 1 int type
            var tuple2 = Tuple.Create<intstringstringstring>(1, "Khumesh""EDUDOTNET""IT-Solution");
            Console.WriteLine(tuple2.Item1);
            Console.WriteLine(tuple2.Item2);
            Console.WriteLine(tuple2.Item3);
            Console.WriteLine(tuple2.Item4);
            Console.WriteLine("Enjoying With Tuple.......... :)");
            Console.ReadLine();
        }
    }
}

0 comments:

Post a Comment