A tuple is a generic container that can contain different data types. A tuple can hold 1 to 8 elements of different data types.
A tuple can be defined with the following syntax:
Tuple<data_type, ...> tuple_name = Tuple.Create(values, ...);
data_type
: This is the data type of the tuple elements. The data type of each element is defined separately.Create(values)
: This method creates a tuple with the given values. Values are written according to the data types mentioned earlier.For example, the following syntax creates a tuple of one integer, an array of float, and a string value:
Tuple<int, float[], string> myTuple = Tuple.Create(102, new float[] {1.1, 2.2, 3.3}, "Educative");
Let’s consider the following example:
// Instantiate a 3-Item Tuple: Int, an Array of Floats and a StringTuple<int, float[], string> myTuple = Tuple.Create(102, new float[] {1.1f, 2.2f, 3.3f}, "Educative");// Access a Tuple itemConsole.WriteLine(myTuple.Item1); // Output: 102Console.WriteLine(myTuple.Item2); // Output: System.Singles[]Console.WriteLine(myTuple.Item3); // Output: Educativeforeach (float theNumber in myTuple.Item2){Console.Write( $"{theNumber} "); // Output: 1.1 2.2 3.3}
Line 2: We create a Tuple
class object and assign values.
Lines 5–6: We print the Tuple
items to the console.
Lines 9–12: A foreach
loop prints the values of the array object in the Tuple
.
Free Resources