Tuple - .NET 4.0 new feature
- by nmarun
Something I hit while playing with .net 4.0 – Tuple. MSDN says ‘Provides static methods for creating tuple objects.’ and the example below is: 1: var primes = Tuple.Create(2, 3, 5, 7, 11, 13, 17, 19);
Honestly, I’m still not sure with what intention MS provided us with this feature, but the moment I saw this, I said to myself – I could use it instead of anonymous types.
In order to put this to test, I created an XML file:
1: <Activities>
2: <Activity id="1" name="Learn Tuples" eventDate="4/1/2010" />
3: <Activity id="2" name="Finish Project" eventDate="4/29/2010" />
4: <Activity id="3" name="Attend Birthday" eventDate="4/17/2010" />
5: <Activity id="4" name="Pay bills" eventDate="4/12/2010" />
6: </Activities>
In my console application, I read this file and let’s say I want to pull all the attributes of the node with id value of 1.
Now, I have two ways – either define a class/struct that has these three properties and use in the LINQ query or create an anonymous type on the fly. But if we go the .NET 4.0 way, we can do this using Tuples as well. Let’s see the code I’ve written below:
1: var myActivity = (from activity in loaded.Descendants("Activity")
2: where (int)activity.Attribute("id") == 1
3: select Tuple.Create(
4: int.Parse(activity.Attribute("id").Value),
5: activity.Attribute("name").Value,
6: DateTime.Parse(activity.Attribute("eventDate").Value))).FirstOrDefault();
Line 3 is where I’m using a Tuple.Create to define my return type. There are three ‘items’ (that’s what the elements are called) in ‘myActivity’ type.. aptly declared as Item1, Item2, Item3. So there you go, you have another way of creating anonymous types.
Just out of curiosity, wanted to see what the type actually looked like. So I did a:
1: Console.WriteLine(myActivity.GetType().FullName);
and the return was (formatted for better readability):
"System.Tuple`3[
[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],
[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],
[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]
]"
The `3 specifies the number of items in the tuple. The other interesting thing about the tuple is that it knows the data type of the elements it’s holding. This is shown in the above snippet and also when you hover over myActivity.Item1, it shows the type as an int, Item2 as string and Item3 as DateTime. So you can safely do:
1: int id = myActivity.Item1;
2: string name = myActivity.Item2;
3: DateTime eventDate = myActivity.Item3;
Wow.. all I can say is:
HAIL 4.0.. HAIL 4.0.. HAIL 4.0