Editorials

Tuples ? Dot Net 4 Generic Classes


Featured Article(s)
Troubleshooting problems with SQL Server 2008 R2 Merge Replication
In this article, Alexander Chigrik explains some problems that you can have when you work with SQL Server 2008 R2 merge replication.

Featured White Paper(s)
All-At-Once Operations
Written by Itzik Ben-Gan with SolidQ

SQL supports a concept called all-at-onc… (read more)

Tuples – Dot Net 4 Generic Classes
I think Tuples released in the Dot Net 4 Framework are the coolest thing. They are really handy allowing you to quickly define structured data without the extra work of defining a Class or a Struct for passing and comparing data having multiple properties.

Tuples are not a new concept…in fact, they are a concept that’s been used in databases for a long time.

The beauty of a Tuple is that you can define a new object on the fly having multiple properties, and each is strongly typed.

You can create a Tuple using explicit typing

Tuple<int, string, string> person = { 123, “Benjamin”, “Taylor” };

or implicit typing

var person = { 123, “Benjamin”, “Taylor” };

Tuples are convenient for returning more than one data element from a method call. This is easier than using ref or out parameters more closely linking methods.

Tuples are read only populated only upon instantiation. They are referenced through the implicit property named attribute for each property. In the case of my Person example, the properties are set when the person Tuple is instantiated. The first property is accessed through person.Item1. The second (my first name) is accessed through person.Item2 and the last name is person.Item3.

Each of the properties of a Tuple is strongly typed and support all the characteristics of each individual type without boxing.

You can even compare Tuples using the Equals method

bool Test = t1.Equals(t2);

t1==t2 will only test if they point to the same object since Tuples are reference objects just as any other class.

So, if you need a quick way to maintain or pass around a more complex object without creating a permanent class or struct, Tuples are a great way to go. Since they are read only, they make great immutable objects, resulting in more thread safe structures.

Are you a Tuple guru? Would you like to provide more information regarding the history of Tuples in other systems? Would you like to share how you have used Tuples in your systems? Send your comments to btaylor@sswug.org.

Cheers,

Ben

$$SWYNK$$

SSWUGtv
With Stephen Wynkoop
Michael Crump talks about development with #sql2012 on the show today – important tips and more.
Watch the Show