Tuple
January 6, 2011 Leave a comment
Tuple is a new class in the .Net 4.0 framework which allows you to hold up to 8 components in a single class. The alternative is creating a specific class with properties for each component. This makes this class ideal for the following situations:
1. Returning multiple values from a method without the use of out parameters
2. Pass multiple values to a method using a single class.
3. Collections of Tuples can be used to represent database information or array data.
4. Easy access and manipulation of a data set.
Here’s an example using Tuple<T1, T2>
class Program { static void Main(string[] args) { int dividend, divisor; Tuple<int, int> result; dividend = 136945; divisor = 178; result = IntegerDivide(dividend, divisor); if (result != null) Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", dividend, divisor, result.Item1, result.Item2); else Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor); dividend = Int32.MaxValue; divisor = -2073; result = IntegerDivide(dividend, divisor); if (result != null) Console.WriteLine(@"{0} \ {1} = {2}, remainder {3}", dividend, divisor, result.Item1, result.Item2); else Console.WriteLine(@"{0} \ {1} = <Error>", dividend, divisor); Console.ReadLine(); } private static Tuple<int, int> IntegerDivide(int dividend, int divisor) { try { int remainder; int quotient = Math.DivRem(dividend, divisor, out remainder); return new Tuple<int, int>(quotient, remainder); } catch (DivideByZeroException) { return null; } } }