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
Tuple.Create
Here is the real example of using a tuple to return multiple values from a method.
public Tuple
{
//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.