What is the difference between anonymous type and tuple?
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 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
.