Tuples is not new in programming. It’s using already in Python, F#, and databases. However, it is new in C#. The tuples were introduced in C# 4.0
Creating Tuples
In C#, Tuple is a static class that implements the "Factory" Pattern to create instances of Tuples. you can create an instance of a Tuple using the constructor or the static method "Create".
Tuple has eight overloads:
Overload
|
Description
|
1-tuple, or singleton.
| |
2-tuple, or pair.
| |
3-tuple, or triple.
| |
4-tuple, or quadruple.
| |
5-tuple, or quintuple.
| |
6-tuple, or sextuple.
| |
7-tuple, or septuple.
| |
8-tuple, or octuple.
|
Why Should We Use tuple?
a) Return of Methods : Tuples provide a quick way to group multiple values into a single result, which can be very useful when used as a return of function, without the need to create parameters "ref" and / or "out ".
e.g
Tuple<int, string, DateTime> _cliente = Tuple.Create(1, "Test", new DateTime(1975, 3, 24));
return _cliente;
b) Composite Key in a Dictionary: As everyone know the dictionary is use to make the key value pairs, By using the Tuple user can make the composite key by tuple.
e.g.: Creating the composite key of employee object
Declaration
Dictionary<Tuple<int, int>, employee> lista =
new Dictionary<Tuple<int, int>, employee>();
Use :
Employee emp = new Employee()
{
EmployeeId = 1234,
EmployeeType = 6,
EmployeeName = "Bob",
EmployeeAddress = "w/12 street 12"
};
lista.Add(Tuple.Create(1234, 6), emp);
c) Replace Classes or Structs that are Created Just to Carry a Return or to Fill a List - many time to carry more than two or three values we create the class and by using List object we carry the value. Now we don’t need of it, we can carry the data w/o creating the class object;
List<Tuple<int, string, string, string>> employee = new List<Tuple<int, string, string, string>>();
employee.Add(Tuple.Create(1, "name", "addrees", "designation"));
employee.Add(Tuple.Create(2, "name1", "addrees1", "designation1"));
employee.Add(Tuple.Create(3, "name2", "addrees2", "designation2"));
How to use tuple? How to insert value into tuple and how to retrieve value from tuple?
Creating a simple list object is containing the tuple of 4 items or quadruple
class Program
{
static void Main(string[] args)
{
List<Tuple<int, string, string, string>> employee = new List<Tuple<int, string, string, string>>();
employee.Add(Tuple.Create(1, "name", "addrees", "designation"));
employee.Add(Tuple.Create(2, "name1", "addrees1", "designation1"));
employee.Add(Tuple.Create(3, "name2", "addrees2", "designation2"));
int count = 1;
foreach (var o in employee)
{
Console.WriteLine("{0}.Value of tuple {1} , {2}, {3}, {4}", count, o.Item1, o.Item2, o.Item3, o.Item4);
count += 1;
}
}
}
output
No comments:
Post a Comment