C# Tuple and its use
C# tuple is a data structure Which contains a sequence of elements of different data types. Tuples were available before C# 7.0, but they were unproductive and had no language support. C# 7.0 introduces better tuples feature that enables semantic names for the fields of a tuple using new, more efficient tuple types. C# 7 introduced ValueTuple
to reduce the limitations of Tuple and it is more easier to work with Tuple.
Syntax
Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
an example below creates a tuple with four elements:
Tuple<int, string, string, string > Customer = new Tuple <int, string, string, string >(1, "Shyam", "Nepal","Kathmandu");
We can use Tuples in the following Cases:
- If we want to return multiple values, from one method without using out or ref parameters.
- If we want to pass multiple values to one method through a single parameter.
- When we want to hold a database record or some values temporarily without creating a separate class.
Implementation:
using System;
namespace CSharpTupule
{
class Program
{
static void Main(string[] args)
{
var Result = Calculate(12, 8);
Console.WriteLine("Sum: " + Result.Item1);
Console.WriteLine("Multiply: " + Result.Item2);
Console.WriteLine("Subtraction: " + Result.Item3);
Console.WriteLine("Divide: " + Result.Item4);
Console.ReadLine();
}
public static Tuple<int, int, int, int> Calculate(int x, int y)
{
int Add = x + y;
int Mul = x * y;
int Sub = x - y;
int Div = x / y;
Tuple<int, int, int, int> t = Tuple.Create(Add, Mul, Sub, Div);
return t;
}
}
}
Output: