views:

190

answers:

2

What is the difference between anonymous type and tuple?

+1  A: 

Anonymous types have property names which carry more information, for tuples you don't have this. You can't use anonymous types as return values and parameters though and you can with tuples.

An example of when a tuple is nice is when you want to return multiple values. @Petar Minchev mentions this link which gives a good example.

You may want a Find() method that returns both an index and the value. Another example would be the position in a 2d or 3d plane.

Brian R. Bondy
+3  A: 

A tuple is not an anonymous type, it's a named type. You can use it as a return type or method argument. This code is valid:

Tuple<int, string> GetTuple()
{
    return Tuple.Create(1, "Bob");
}

You can't do this with an anonymous type, you would have to return System.Object instead. Typically, you end up having to use Reflection on these objects (or dynamic in .NET 4) in order to obtain the values of individual properties.

Also, as Brian mentions, the property names on a Tuple are fixed - they're always Item1, Item2, Item3 and so on, whereas with an anonymous type you get to choose the names. If you write:

var x = new { ID = 1, Name = "Bob" }

Then the anonymous type actually has ID and Name properties. But if you write:

Tuple.Create(1, "Bob")

Then the resulting tuple just has properties Item1 and Item2.

Aaronaught