What is a Tuple in C# and When to Use It
Introduction
Tuple is a generic static class that was added to C# 4.0 and it can hold any amount of elements, and they can be any type we want. So using tuple, we can return multiple values.One great use of tuple might be returning multiple values from a method. It provides an alternative to "ref" or "out" if you have a method that needs to return multiple new objects as part of its response.
A tuple allows you to combine multiple values of possibly different types into a single object without having to create a custom class. This can be useful if you want to write a method that for example returns three related values but you don't want to create a new class.
We can create a Tuple using the Create method. This method provide to 8 overloads, so we can use a maximum of 8 data types with a Tuple.
Followings are overloads
Create(T1)- Tuple of size 1
Create(T1,T2)- Tuple of size 2
Create(T1,T2,T3) – Tuple of size 3
Create(T1,T2,T3,T4) – Tuple of size 4
Create(T1,T2,T3,T4,T5) – Tuple of size 5
Create(T1,T2,T3,T4,T5,T6) – Tuple of size 6
Create(T1,T2,T3,T4,T5,T6,T7) – Tuple of size 7
Create(T1,T2,T3,T4,T5,T6,T7,T8) – Tuple of size 8
Example
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace EDUDOTNET_TupleDemo
- {
- class EDUDOTNET
- {
- static void Main(string[] args)
- {
-
- var tuple = Tuple.Create<string, string, string>("EDUDOTNET", "IT", "SOLUTION");
- Console.WriteLine(tuple);
-
- var tuple1 = Tuple.Create<int, string>(51, "CTO-EDUDOTNET");
- Console.WriteLine(tuple1);
-
-
-
- var tuple2 = Tuple.Create<int, string, string, string>(1, "Khumesh", "EDUDOTNET", "IT-Solution");
- Console.WriteLine(tuple2.Item1);
- Console.WriteLine(tuple2.Item2);
- Console.WriteLine(tuple2.Item3);
- Console.WriteLine(tuple2.Item4);
- Console.WriteLine("Enjoying With Tuple.......... :)");
- Console.ReadLine();
- }
- }
- }