Friday, October 17, 2014

Tuple Type in C#4.0

What is Tuple type ? 
Tuple is new class type added in C#4.0. Tuple type allows to create data structure which is consist of specific type and specific number of elements. In the following post its about basic of Tuple type, how and where to use this new type in your code.

How to create Tuple type object
Following code show how you can create and use this class type.
?
1
2
3
Console.WriteLine("How to create and use");
Tuple<int, string> tuple = new Tuple<int, string>(1, "Nilesh");
Console.WriteLine(tuple.Item1 + "-" + tuple.Item2);
One way to create object is just make use of constructor and create the Tuple object.
?
1
2
3
Tuple<int, string> tuple1 = Tuple.Create(2, "ab1");
Console.WriteLine(tuple1.Item1 + "-" + tuple1.Item2);
Console.WriteLine();
Second way is make use of Create Static method supported by Tuple class and create object.

Refer Element of Tuple Object
As you see in both example element of Tuple get referred using name Item1 and Item2, so this is predefined name for the element by .net framework only. So to refer element in Tuple object you need to write "Item+number_of_the_element".

Constrain
You cannot change value of the the property of Tuple object.
?
1
2
3
// after creation of object this is not possible
// this gives compile time error
tuple1.Item1 = 100;

C# allows to create Tuple object with the 7 different type element. 
?
1
2
3
4
5
6
7
Create(T1) Creates a new 1-tuple, or singleton.
Create(T1, T2) Creates a new 2-tuple, or pair.
Create(T1, T2, T3) Creates a new 3-tuple, or triple.
Create(T1, T2, T3, T4) Creates a new 4-tuple, or quadruple.
Create(T1, T2, T3, T4, T5) Creates a new 5-tuple, or quintuple.
Create(T1, T2, T3, T4, T5, T6) Creates a new 6-tuple, or sextuple.
Create(T1, T2, T3, T4, T5, T6, T7) Creates a new 7-tuple, or septuple.

What to do if you want to have more than 8 values ?
Last variation of Tuple creation allows to create Tuple object with more than 8 different element. 
?
1
Create(T1, T2, T3, T4, T5, T6, T7, T8) Creates a new 8-tuple, or octuple.
in this T8 element is of type Tuple only that means if you want to create tuple more than 8 it will be like this 
?
1
2
3
var num = new Tuple<int, int, int, int, int, int, int,
                 Tuple<int>>(1, 2, 3, 4, 5, 6, 7,
                 new Tuple<int>(8));

Use Of Tuple type
To Pass data To methods
Sometime we just create class or structure to just pass data to method, creation of this extra class or structure in code can be avoided by using Tuple object to pass data.
Following is example of this where object of Tuple used to pass int and string data. And its shows that we can also create list of Tuple object and pass to method for processing. 
?
1
2
3
4
5
6
7
8
ProcessData(new Tuple<int, string>(1, "Pranay"));
 
Listint, String>> lst = new Listint, string>>();
lst.Add(new Tuple<int, string>(1, "Pranay"));
lst.Add(Tuple.Create(2, "ab1"));
lst.Add(Tuple.Create(1, "abcdef"));
lst.Add(Tuple.Create(3, "cd2"));
ProcessListOfData(lst);

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//Process single Tuple object
public static void ProcessData(Tuple<int, string> tup)
{
    Console.WriteLine("ProcessData");
    Console.WriteLine(tup.Item1 + "-" + tup.Item2);
    Console.WriteLine();
}
//Process list of Tuple object
public static void ProcessListOfData(Listint, String>> lst)
{
    Console.WriteLine("ProcessListOfData");
    var data = lst.Where(x => x.Item1 == 1).Select(x => x);
    foreach (var tup in data)
    {
       Console.WriteLine(tup.Item1 + "-" + tup.Item2);
    }
    Console.WriteLine();
}

To Return From the Method 
Tuple can be used to return data from method where you want to return more than one value or list of object without creating extra class or structure for carrying data. 
Following is example of returning data type. 
?
1
2
var data = ReturnTupleData();
Console.WriteLine(data.Item1 + "-" + data.Item2);

?
1
2
3
4
public static Tuple<int, string> ReturnTupleData()
{
    return new Tuple<int, string>(1, "pranay");
}
As you can see it use Tuple object to return int and string data which is not possible with the normal method because we only have one return type. 

To Return Anonymous Type 
Following is example of using Tuple with linq where most of the time we return anonymous type from the method because we just have to select only require number of property from set of property object have. 
?
1
2
3
4
5
foreach (var tup in ProcessListOfDataAndReturn(lst))
{
     Console.WriteLine(tup.Item1 + "-" + tup.Item2+"-" + tup.Item3);
}
Console.WriteLine();

?
1
2
3
4
5
6
7
8
9
10
11
12
public static IEnumerableint, string, int>> ProcessListOfDataAndReturn(Listint, String>> lst)
{
     Console.WriteLine("ProcessListOfDataAndReturn");
     var data = from tup in lst
                select new Tuple<int, string, int>
                    (
                        tup.Item1,
                        tup.Item2,
                        tup.Item2.Length
                     );
     return data.ToList();
}
You cannot return anonymous type from the method which is one of the constrain. There are other ways to return it from the method which is already discuss by me here Return Anonymous type.
But with the help of Tuple we can easily return Anonymous type data which you can see in above code.

Conclusion
This inbuilt Tuple class in C#4.0 can be use to avoid issue discuss above and also to simplify code at some point 

Full Source code 
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace TupleTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How to crate and use");
            Tuple<int, string> tuple = new Tuple<int, string>(1, "pranay");
            Tuple<int, string> tuple1 = Tuple.Create(2, "ab1");
            Console.WriteLine(tuple.Item1 + "-" + tuple.Item2);
            Console.WriteLine(tuple1.Item1 + "-" + tuple1.Item2);
            Console.WriteLine();
          
            ProcessData(new Tuple<int, string>(1, "Pranay"));
 
            Listint, String>> lst = new Listint, string>>();
            lst.Add(new Tuple<int, string>(1, "Pranay"));
            lst.Add(Tuple.Create(2, "ab1"));
            lst.Add(Tuple.Create(1, "abcdef"));
            lst.Add(Tuple.Create(3, "cd2"));
            ProcessListOfData(lst);
 
            Console.WriteLine("ReturnTupleData");
            var data = ReturnTupleData();
            Console.WriteLine(data.Item1 + "-" + data.Item2);
            Console.WriteLine();
 
            foreach (var tup in ProcessListOfDataAndReturn(lst))
            {
                Console.WriteLine(tup.Item1 + "-" + tup.Item2+"-" + tup.Item3);
            }
            Console.WriteLine();
 
            Console.ReadLine();
        }
 
        public static void ProcessData(Tuple<int, string> tup)
        {
            Console.WriteLine("ProcessData");
            Console.WriteLine(tup.Item1 + "-" + tup.Item2);
            Console.WriteLine();
        }
 
 
        public static void ProcessListOfData(Listint, String>> lst)
        {
            Console.WriteLine("ProcessListOfData");
            var data = lst.Where(x => x.Item1 == 1).Select(x => x);
            foreach (var tup in data)
            {
                Console.WriteLine(tup.Item1 + "-" + tup.Item2);
            }
            Console.WriteLine();
        }
 
        public static Tuple<int, string> ReturnTupleData()
        {
            return new Tuple<int, string>(1, "pranay");
        }
 
        public static IEnumerableint, string, int>> ProcessListOfDataAndReturn(Listint, String>> lst)
        {
            Console.WriteLine("ProcessListOfDataAndReturn");
            var data = from tup in lst
                       select new Tuple<int, string, int>
                       (
                           tup.Item1,
                           tup.Item2,
                           tup.Item2.Length
                       );
            return data.ToList();
        }
    }
}

Leave comment if you have any query or if you like it.

No comments:

Post a Comment