A Responsive Blogger Website, That Take my blog to the next level.

I am a Software Developer, Learning and experementing with .Net Technology and try to put my Learning altogether here.


We have all sections related to .Net Technology, like .Net-C#, Asp.Net, MVC, jQuery, AngularJs, Sharepoint. Find out more...


Following are the some of the Advantages of using this Web site :-

  • Get Update about latest in .Net world.
  • Collection of Useful, Frequently used .Net Solutions.
  • It’s beautiful on every screen size (try resizing your browser!)
by

Let us Learn Tuple-Part1


C#4.0 has introduced a new feature call Tuple.In this article we will start learning about Tuple, how to create it,when to use Tuple and how to access Tuple.

Introduction

C#4.0 has introduced a new feature call Tuple. In this article we will start learning about Tuple, how to create it, when to use Tuple and how to access Tuple. This is a series of articles on Tuples and you can read the entire series of article as listed down
Let us Learn Tuple-Part1
Let us Learn Tuple-Part2 ( Creation of Generic Collections and Accessing the same using Tuple )
Let us Learn Tuple-Part3 ( Tuple and Arrays )
Let us Learn Tuple-Part4 ( Create MultiKey dictionary using Tuple )
Let us Learn Tuple-Part5 ( LAMBDA with Tuple )
Let us Learn Tuple-Part6 (Tuple Serialization and DeSerialization)
Let us Learn Tuple-Part7 (Last but not the least part)
(A)What is Tuple?
Tuple is an ordered sequence data structure, introduced in C#4.0, that holds heterogeneous objects. It is represented both as an instance class as well as a static class that uses a static method call Create to create item(s) at runtime. The items(s) created by the Create method is also a Tuple. In other words, the Create static method of the Tuple static class returns an instance of a Tuple.
The Create method has eight(8) overloaded method as shown under
public static class Tuple  {  public static Tuple<T1> Create<T1>(T1 item1);  public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2);  public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3);  public static Tuple<T1, T2, T3, T4> Create<T1, T2, T3, T4>(T1 item1, T2 item2, T3 item3, T4 item4);  public static Tuple<T1, T2, T3, T4, T5> Create<T1, T2, T3, T4, T5>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5);  public static Tuple<T1, T2, T3, T4, T5, T6> Create<T1, T2, T3, T4, T5, T6>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6);  public static Tuple<T1, T2, T3, T4, T5, T6, T7> Create<T1, T2, T3, T4, T5, T6, T7>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7);  public static Tuple<T1, T2, T3, T4, T5, T6, T7, Tuple<T8>> Create<T1, T2, T3, T4, T5, T6, T7, T8>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, T8 item8);  }  
As can be figure out that, the last argument is again another tuple. This clearly reveals that we can add another tuple item in the 8th argument.
It resides under the System namespace.
(B)Why Tuple?
We know that any called function returns a single value. However, there are times where we may need to return multiple values to the calling function. Tuple precisely serves that purpose.
Let us observe the above statement with an example.
static Tuple<List<int>, List<int>> GetEvenOddNumbers()  {      var numbers = Enumerable.Range(1, 20); //generate numbers between 1 to 20      return           Tuple          .Create          (            numbers.Where(i=>i%2==0).ToList() //find even numbers list            , numbers.Where(i => i % 2 != 0).ToList() //find odd numbers list          );  }  
In the above function, we are generating a series of numbers between 1 to 20 and then segregating the even and odd numbers list and finally returning the same by using Tuple. We can figure out that, the Tuple returns two values of type List<int>, List<int>.This indicates that, the function GetEvenOddNumbers() is capable of returning more than one value to the calling function.
(C)When to use Tuple?
Tuples finds it's usage in multiple places. Some of them are listed below
1. Return multiple values from a method or function
In earlier versions of dotnet(before 4.0), we can achive to return multiple values from a function by using OUT parameters e.g
class MainClass  {          public static void Main(string[] args)          {              var evenNumList = new List<int>();              var oddNumList = new List<int>();                GetEvenOddNumbersUsingOutParameters(out evenNumList, out oddNumList);                        }            private static void GetEvenOddNumbersUsingOutParameters(out List<int> evenNumList,                                                                   out List<int> oddNumList)          {              var numbers = Enumerable.Range(1, 20); //generate numbers between 1 to 20              evenNumList = numbers.Where(i => i % 2 == 0).ToList();              oddNumList  = numbers.Where(i => i % 2 != 0).ToList();          }            }   
Some disadvantages of the above program can be listed as under
  1. Declaration and initialization of extra variables which on the other hand indicates more space complexity and unnecessary object creation.
  2. Using OUT parameter breaks the Single Responsibility Principle
  3. It is slower to access since it involves double indirection problem.
For a better design perspective, we can create a Custom class and use it to return multiple values from a function. But this approach has it's own limitation as it may not be equally feasible all the time to do so and moreover can cause extra code size.
Another approach can be a collection like Dictionary, HashTable or ArrayList but again a seek time for the look-up is involve
And the most common disadvantage to all of the above approach is that they are not thread safe since they are instance members of some kind as opposed to Tuple since it is static and so are it's member(s)
2. Passing multiple values from calling function to a called function
Let us consider the below example
public static void Main(string[] args)  {                           var names = new List<string>() { "Name1", "Name2", "Name3", "Name4" };              var index = new List<int>() { 1, 2, 3, 4 };              var nameIndexTuple  = new Tuple<List<string>, List<int>>(names, index);              ShowItemPosition(nameIndexTuple);             }    private static void ShowItemPosition(Tuple<List<string>, List<int>> nameIndexTuple)  {                  //do something interesting  }  
In the above program, we have created a string and integer collection of items, bundled them inside a Tuple and finally passing them as a single parameter to the called function ShowItemPosition.
We can also achieve the same by using the above describe methods but again with the same disadvantage. Params can serve the purpose but it has it's own limitation since an array is a collection of same type. We can, however, create an object datatype param but it will be tedious to read and manipulate as it involves a huge boxing and unboxing.
Tuple on the other hand, is much more cleaner approach.
(D)How to create Tuple in C#?
We can create Tuple in one of the two below listed ways
  1. By creating a class instance of Tuple Class
    E.g.
    Tuple<string, int, List<string>> studentTupleInstance = new Tuple<string, int, List<string>>(      "Rajlaxmi", 4      , new List<string> { "Mathematics","English","Science and Social Science","Hindi"     });                    
    In the above example we have created an instance (studentTupleInstance) of the Tuple class which contains a string (Student Name),an integer (Student age) and a collection of string (Collection of Subjects). This is an example of 3-Tuple or Triple.
  2. By using the static Create method of Tuple Class
    E.g.
    Tuple<string, int, List<string>> studentTupleCreateMethod = Tuple.Create(        "Rajlakshmi", 4,          new List<string> { "Mathematics","English",                                            "Science and Social Science","Hindi"                                          });                    
    In the above example we have created the Tuple (studentTupleCreateMethod) by using the static Create method of the Tuple class which contains a string (Student Name),an integer (Student age) and a collection of string (Collection of Subjects).
(E)How to access Tuple in C#?
Accessing the items of Tuples as very simple. Tuples items or properties are of Generic Types and henceforth, they don't have any concrete names. In-order to access the Tuple items, we need to invoke the dot (.) operator preceded by the Tuple name as shown below


In the above figure, Item1 represents the first item of the Tuple ((Student Name) which is of type string.

The second item (Student age)is of type int and the last one (Collection of Subjects) is of List<string>.

Being generic, it reduced the overhead of boxing and unboxing which could be on the other hand a tedious task with Objects or Dynamics

References

Tuple Class
An introduction to Tuple

Conclusion

In this introductory article with Tuple, we learnt about What a Tuple is Why we need Tuple, When to use it, How to create Tuple and How to access the same in C#. Hope this will be helpful. More to come in the following series. Zipped file attached.

Inoreader is a light and fast RSS Reader. Follow us on Twitter and Facebook.

0 comments :