Tuesday, July 12, 2011

C# : Tupel


Array can combine objects which have same type, but some time we need to combine objects which have different types. For that in Framework 4.0, Microsoft introduces new feature Tupel. Tuple provides facility to combine of different type of object in one object. Tupel is derived from programing language such as  F# or like Haskell in Python.  With .NET 4 , Tupel is available for all .NET languages.

Example
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //get age from passed birthdate
           Tuple<int,int,int> age = calculateAge(new DateTime(1982,4,4));
            //Tuple value can access with age.Item1.........
           Console.WriteLine("Age {0} years, {1} months, {2} days", age.Item1, age.Item2, age.Item3);
           Console.ReadKey();
        }

        public static Tuple<int, int, int> calculateAge(DateTime birthDate)
        {
            DateTime currDate = DateTime.Today;
            int ageInYears = currDate.Year - birthDate.Year;          
            int ageInMonths = currDate.Month - birthDate.Month ;
            int ageInDays = currDate.Day - birthDate.Day;
            if (ageInDays < 0)
            {
                ageInDays += DateTime.DaysInMonth(currDate.Year, currDate.Month);
                ageInMonths--;
            }

            if (ageInMonths < 0)
            {
                ageInMonths += ageInMonths += 12; ;
                ageInYears--;
            }
            //create tuple with static function "Create" of Tuple class
            return Tuple.Create<int, int, int>(ageInYears, ageInMonths, ageInDays);
        }
    }
}
/*----------------------------------------------------------------------
Output 
 Age 29 years, 3 months, 8 days
------------------------------------------------------------------------
*/
In .NET 4, we can define 8 generic Tuple. Tuple can create with static function Create of Tuple class. In case more than 8 element in Tuple we should use nested Tuple within Tuple defination at last element of Tuple. Last parameter named as TRest. You must pass TRest a Tuple itself. Otherwise it throws ArgumentException exception. Finally, the functionality of Tuple as bellow :

Public class Tuple<t1,t2,t3,t4,t5,t6,t7,trest> 

Example of more than 8 element
var obj = Tuple.Create<string,string,string,int,int,int,double,Tuple<int,DateTime>>("Ram","Laxman","Bhrat",500,2,85,1.37,Tuple.Create<int,DateTime>(65,"27-Jan-2004"));
In above example, you can see last parameter is Tuple type itself. Hence, with this meathod we can create a Tuple any numbers of items.

No comments:

Post a Comment