C# - Tuples
A Tuple is a data structure that allows the creation of a sequence of elements each of a different data type. Meaning that they can have multiple objects with properties within the same data structure without having to create a new type for each.
Below is an example scenario where a tuple can be used. A function is used to get two values and then work out the area of a shape.
static Tuple<double,double> Getvalues()
{
Console.WriteLine("Enter the height: ");
double userH = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the width: ");
double userW = double.Parse(Console.ReadLine());
return Tuple.Create(userH, userW);
}
We set the return type to tuple, and inside the angle brackets give the data types we want to return.
static void areatriangle()
{
Tuple<double, double> values = Getvalues();
triangle tri1 = new triangle(values.Item1,values.Item2);
tri1.CalculateArea();
}
We create a tuple using the same two data types we assigned above. Set the name, and value of the variable to be the function above. Allowing us to access each item in the tuple individually