Sep 11, 2012

Tuple in C#

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.

In this post, I am sharing an example, how tuple can be used to return multiple values from a method.

In the example, we are passing two int values to the method and method is performing four mathematical operations (add, subtract, multiplication, division) and returning a tuple with 3 int 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);
        }      
    }
}
OUTPUT

    Choose :
  • OR
  • To comment
4 comments:
Write Comments
  1. Nice one..very useful post with point to point deatils..

    ReplyDelete
  2. Useful article !! Thanks for sharing !!

    ReplyDelete
  3. Useful article , Thanks for sharing the knowledge !

    ReplyDelete