Sunday, September 5, 2010

Tuple in C# 4.0

C# 4.0 includes a new feature called Tuple. Tuple provides us with a way to group elements of disparate data types together.This is present in functional languages like Haskell and also dynamic languages like Python.

Consider the following code:
It creates a tuple storing name and age of person.

We can create nested tuples as shown below:

The most important thing to know about the Tuple type is that it is a class, not a struct, and thus will be allocated upon the managed heap. Each class instance that is allocated adds to the burden of garbage collection. The properties Item1, Item2, and further do not have setters, so you cannot assign them. The Tuple is immutable once created in memory.

It is difficult for developers to choose between Tuples and Anonymous Types as they serve similar purpose. It can be a difficult to make the best choice between those two solutions.

Read more about it here.

No comments:

Post a Comment