What is Tuples in C# 4.0


Tuple is a static class which allows the developer to create an object with some properties in it without creating a class for it. Lets say you want to send five marks of a student from a function to calling place, instead of creating a class with five properties you can use the Tuple class and assign those values and send the tupe object to the calling place.

In C# 4.0 a new type called Tuple is introduced. Commonly it is used to return multiple values from a method without using out parameters or Custom types.

We can create Tuple like the following,


new Tuple()

new Tuple("name", 1995);

Tuple.Create("name", 1995);


Here is the real example of using a tuple to return multiple values from a method.


public Tuple GetDivAndRemainder(int i, int j)
{
//Creating a tuple with two integer values in it Tuple.Create(i/j, i%j);

}

public void CallMethod()

{

var tuple = GetDivAndRemainder(10,3);



//Access the values based on its position

//Item1 will give a int

//Item2 will give int

Console.WriteLine("{0} and {1}",

tuple.item1, tuple.item2);

}



Advantages:



No need of declaring out parameters
No need of creating cutom type objects to return mutiple values
Limitation:

At the receiving end, we may not know, what data type is returned at what position in the tuple.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: