Introduction
Tuples were available before C# 7.0, but they were inefficient and had no language support. Issues in tuples in previous versions were that the elements in a tuple could only be referenced as Item1, Item2 and so on. C# 7.0 introduces improved tuples feature that enables semantic names for the fields of a tuple using new, more efficient tuple types.
Tuple is a class in C#.
Let us dive into it.
- class Program
- {
- static void Main(string[] args)
- {
- var Result = Calculation(9, 3);
- Console.WriteLine("Addition " + Result.Item1);
- Console.WriteLine("Multiplication " + Result.Item2);
- Console.WriteLine("Subtraction " + Result.Item3);
- Console.WriteLine("Division " + Result.Item4);
- Console.ReadLine();
- }
- public static Tuple<int,int,int,int> Calculation(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;
- }
- }
- }
Slightly changed in C#
- class Program
- {
- static void Main(string[] args)
- {
- var Result = SumResult(9, 3);
- Console.WriteLine("Addition " + Result.Item1);
- Console.WriteLine("Multiplication " + Result.Item2);
- Console.WriteLine("Subtraction " + Result.Item3);
- Console.WriteLine("Division " + Result.Item4);
- Console.ReadLine();
- }
- public static (int,int,int,int) SumResult(int x, int y)
- {
- int Add = x + y;
- int Mul = x * y;
- int Sub = x - y;
- int Div = x / y;
- return (Add, Mul, Sub,Div);
- }
- }
Feature of Tuple
- class Program
- {
- static void Main(string[] args)
- {
- var (Addition, Multiplication, Subtraction, Division) = SumResult(9, 3);
- Console.WriteLine("Addition " + Addition);
- Console.WriteLine("Multiplication " + Multiplication);
- Console.WriteLine("Subtraction " + Subtraction);
- Console.WriteLine("Division " + Division);
- Console.ReadLine();
- }
- public static (int,int,int,int) SumResult(int x, int y)
- {
- int Add = x + y;
- int Mul = x * y;
- int Sub = x - y;
- int Div = x / y;
- return (Add, Mul, Sub,Div);
- }
- }
We can define in this way:
- static void Main(string[] args)
- {
- var result = SumResult(9, 3);
- Console.WriteLine("Addition " + result.Addition);
- Console.WriteLine("Multiplication " + result.Multiplication);
- Console.WriteLine("Subtraction " + result.Subtraction);
- Console.WriteLine("Division " + result.Division);
- Console.ReadLine();
- }
- public static (int Addition, int Multiplication, int Subtraction, int Division) SumResult(int x, int y)
- {
- int Add = x + y;
- int Mul = x * y;
- int Sub = x - y;
- int Div = x / y;
- return (Add, Mul, Sub, Div);
- }
Conclusion
In this article, we studied about tuples in C#.