C# 4.0 included a new feature called Tuple. A tuple is a data structure that has a specific number and sequence of elements.
Tuple can be used in several ways. Let’s see, how tuple can be used to return multiple values from a method.
In the example, we are passing two integer values to the method and method is performing four mathematical operations (add, subtract, multiplication, division) and returning a tuple with 3 integer and 1 double values for these operations.
- using System;
- namespace ConsoleApplication1
- {
- class clsMain
- {
- static void Main(string[] args)
- {
- clsTuple objTuple = new clsTuple();
- var tuple = objTuple.Operations(10, 3);
- Console.WriteLine("Sum:{0}, Subtract:{1}, Multiply :{2}, Division:{3}", tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4);
- System.Threading.Thread.Sleep(2000);
- }
- }
- class clsTuple
- {
- public Tuple < int, int, int, double > Operations(int i, int j)
- {
- return Tuple.Create(i + j, i - j, i * j, Convert.ToDouble(i) / j);
- }
- }
- }