A Tuple in C# is an ordered sequence, means each object being of a specific type. It is introduced in C# 4.0 with dynamic programming. It can be useful when returning more than one value from a method.
A Tuple has many items. Each item can have any data type. The Tuple class provides a unified syntax for creating objects with typed fields.
Visual studio provides the intellisense for tuple object depends upon the data type of the item.
Methods
//Creates a new 1-tuple, or singleton. public class Tuple <T1> //Creates a new 2-tuple, or pair. public class Tuple <T1, T2> //Creates a new 3-tuple, or triple. public class Tuple <T1, T2, T3> //Creates a new 4-tuple, or quadruple. public class Tuple <T1, T2, T3, T4> //Creates a new 5-tuple, or quintuple. public class Tuple <T1, T2, T3, T4, T5> //Creates a new 6-tuple, or sextuple. public class Tuple <T1, T2, T3, T4, T5, T6> //Creates a new 7-tuple, or septuple. public class Tuple <T1, T2, T3, T4, T5, T6, T7> //Creates a new 8-tuple, or octuple. public class Tuple <T1, T2, T3, T4, T5, T6, T7, T8>
A Tuple can be instantiated in two ways:
1. Constructor
var tuple = new Tuple<int, string>(10, "Hello World");
2. Static method
var tuple = Tuple.Create(10.10, "Hello World", 50);
Tuples are commonly used in four ways:
1. To represent a single set of data. For example, a tuple can represent a database record, and its components can represent individual fields of the record.
2. To provide easy access to, and manipulation of, a data set.
3. To return multiple values from a method without using out parameters.
4. To pass multiple values to a method through a single parameter.
Example
Tuple<int, string> tuple = new Tuple<int, string>(10, "Hello World!"); Console.WriteLine(tuple.Item1); // will print 10 Console.WriteLine(tuple.Item2); // will print "Hello World!"
Related articles
- Tuple Class (msdn.microsoft.com)
- Tuple in C# (afana.me)
Hi Suraj, Its always informative to read ur Blog… I was totally unaware of “Tuple” thing in C#.
Thanks, Man. Keep up….
Also, there’s a concept of Lazy Initialization in C#(System.Lazy).. Hope u cover this next, u already have not…
🙂
LikeLike
Hi Akash,
Thanks for your kind words. I am pleased to see that you are enjoying my blog.
And sure I will try to cover lazy initialization in upcoming posts. It’s been added to my todo list now.
Regards,
Suraj
LikeLike
Reblogged this on Akash A and commented:
Tuple in C# 4.0
LikeLike
Wonderful post! We are linking to this particularly
great article on our website. Keep up the good writing.
LikeLike