Summary of tuples:
Arrays merge objects of the same type, while tuples merge objects of different types. Tuples originated from function programming languages (such as F #).
Tuples are frequently used in these languages. In N stare 4, tuples can be used in all NET languages through. NET Fmmework.
. NET 4 defines eight generic Tuple classes and a static Tuple class, which are used as the factory of tuples. Different generic Tuple
Class supports different numbers of elements. For example, Tuple <T1> contains-elements, Tuple <T1, T2> contains two elements, and so on.
1. Example 1
Private Tuple <int, int> Divide (int dividend, int divisor)
{
Int result = dividend/divisor;
Int reminder = dividend % divisor;
Return Tuple. Create <int, int> (result, reminder); // returns the tuples of two elements of the same type.
}
-------- Test -------------
Private void button#click (object sender, EventArgs e)
{
Tuple <int, int> result = Divide (13, 2 );
Console. WriteLine ("result of divison: {0}," +
"Reminder: {1}", result. Item1, result. Item2); // use the item1 and item2 attributes to access the items of the tuples.
}
------- Result -------------
Result of divison: 6, reminder: 1
2. Example 2
Private Tuple <int, string> MyTest2 (int dividend, string Name)
{
Int result = dividend/2;
String name = "Hello," + Name;
Return Tuple. Create <int, string> (result, name); // returns the tuples of two elements of different types.
}
-------- Test -------------
Private void button2_Click (object sender, EventArgs e)
{
Tuple <int, string> result = MyTest2 (13, "limin ");
Console. WriteLine ("result of divison: {0}," +
"Name: {1}", result. Item1, result. Item2); // use the item1 and item2 attributes to access the items of the tuples.
}
------- Result -------------
Result of divison: 6, Name: Hello, limin
3. Example 3
If there are more than 8 items in the tuples, you can use the Tuple class with 8 parameters. The last template parameter is TRest,
It indicates that a tuples must be passed to it. In this way, you can create tuples with any parameters.
This function is described below:
Public class Tuple <T1, T2, T3, T4, T5, T6, T7, TRest>
The last template parameter is of the tuples type, so you can create any number of tuples:
Var tuple = Tuple. Create <string, int, double,
Tuple <int, int> (
"Stephen", "Alina", "Nagel", 2009,6, 2, 1.37,
Tuple. Create <int, int> (52,3490 ));
Author: limlimlim