Monday, May 30, 2011

Tuple

Tuple<T> is a new generic class in .NET 4.0 that makes it easy to combine multiple items of any type into one object. The concept is similar to any array. The advantage to a Tuple<T> is that the elements are individually typed and can be accessed without a subscript. This alleviates the danger of going outside of an array's bounds.


Tuple<int, string, char> x;


Tuples can have between 1 and 8 elements.
They can be instantiated either by using "new" or Tuple.Create()


Tuple<int, string, char> x = new Tuple<int, string, char>(1, "asdf", 'c');
Tuple<bool, float, decimal> y = Tuple.Create(true, 1.0f, 2.3m);


The items in a Tuple can be accessed using Tuple.Item1, Tuple.Item2, etc.


MessageBox.Show(y.Item2.ToString());


That's really all there is to it.
This is nice when you have multiple items that go together but don't really fit into a class.

Have fun.

No comments:

Post a Comment