Monday, 10 April 2017

Tuple in Asp.Net C#


Introduction
In this post we will learn what is tuple and how to use tuple using c#. Why do we need to use tuple in which situations .

What is
This Tuple concept comes in c# 4.0. In C#, tuples are used to store data. It’s just like a variable, but in order for it to be a tuple it must contain more than one value. Each instance of a tuple has a fixed number of items within it (and each item has its own distinct type, eg. a variable or an int), 

At the time of Tuple creation we define the order of element in a Tuple. Tuples have all read only properties means we can not change them once created. Tuple size is fixed and cannot change after declaration.

Why Tuple
Using Tuple without the use of out parameter we can return a dataset from class method.
Using Tuple we can pass multiple values by using a single parameter.

Tuple Class
Tuple class is static. We can access all the tuple class method without creating object of this class. Tuple class have 8 overloaded create methods.


Tuple.Create<t1>
 
Tuple.Create<t1, t2>
 
Tuple.Create<t1, t2, t3>
 
Tuple.Create<t1, t2, t3, t4>
 
Tuple.Create<t1, t2, t3, t4, t5>
 
Tuple.Create<t1, t2, t3, t4, t5, t6>
 
Tuple.Create<t1, t2, t3, t4, t5, t6, t7>
 
Tuple.Create<t1, t2, t3, t4, t5, t6, t7, t8>


Practice 
By using tuple class constructor we can create the object of tuple.

Tuple<intboolstring> tuple = new Tuple<intboolstring>                                        (101, true"JP");


Here i am sharing my tested code for tuples better explanation and understanding.
public void TupleMethodEx(Tuple<string, string, int> tupleParameter)
    {
        var testTuple = tupleParameter;
        Console.WriteLine("Name:{0}, Address:{1}, Phone:{2}.",
        testTuple.Item1, testTuple.Item2, testTuple.Item3);
    }


Call this method and pass Tuple type parameter.


TestTupleClass objTuple = new TestTupleClass();
objTuple.TupleMethodEx(new Tuple<string, string, int>
                                       ("Jack", "California", 0767876765));
 

No comments:

Post a Comment