Tuesday 16 September 2014

Use of the Tuple class in .NET 4.0

Use of the Tuple class in .NET 4.0

Hi Friends,

In this article i will introduce Tuple class and its usage in C#

The Tuple class, which was introduced in .NET 4.0, is handy for passing short-lived objects consisting of multiple related values.
1.What is the Tuple class used for?
The Tuple class is used for short-lived objects consisting of multiple values:
var myTuple = new Tuple<string, int>("Ten", 10);

2.Passing multiple values in a single object
Commonly when you want to pass an object consisting of several values you’d use something like a custom struct or class, or perhaps a generic KeyValuePair object (if you want to pass an object with exactly two data members).
A tuple can contain any number of properties (each generic type parameter results in a read-only property in your tuple object). Each property is automatically namedItem1Item2Item3 etc:
// Group related data
var myName =
new Tuple<string, string, int>("Sujeet "Bhujbal", "SujeetBhujbal".Length);

// Output name info
"My full name is {0} {1} which consists of {2} characters, whitespace excluded.",

Tuples are read-only
Tuples are immutable, their properties do not have any setters, so once a tuple is initialized its values cannot be modified:

A tuple is a class, not a struct
This might not seem that important, but it’s still noteworthy that each tuple is in fact aclass, meaning it will have to be garbage-collected. This in contrast to customstructs, or objects such as generic KeyValuePair objects which are created asstructs by the compiler. Of course, the KeyValuePair comparison is only relevant if your tuple consists of exactly two properties.
Fixed Size      
 The size is set at the time of its creation. If it was created with three items, you cannot add new items.
Of heterogeneous objects
           Each item has a specific and independent of the type of the other item.
As Tuples don’t have an explicit semantic meaning, your code becomes unreadable.

Happy Programming!!

Don’t forget to leave your feedback and comments below!

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Sujeet Bhujbal

No comments:

Post a Comment