Anonymous type and tuple
What is th开发者_C百科e difference between anonymous type and tuple?
Just a little update to this answer since C# 7 is out in the wild. Tuples have super powers now and can sometimes replace anonymous types and classes. Take for example this method that accepts and returns tuples with named properties.
To help illustrate what is possible, the Whatever
function transforms the input shape and values.
void Main()
{
var tupleInput = (Neat: 123, Cool: true);
var tupleOutput = Whatever(tupleInput);
Debug.Assert(tupleOutput.Something == 133);
Debug.Assert(tupleOutput.Another == "True");
}
(int Something, string Another) Whatever((int Neat, bool Cool) data)
{
return (Something: data.Neat + 10, Another: data.Cool.ToString());
}
That's cool.
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
.
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.
Another point in favor of anonymous types would be that you can easily have more than 8 properties. While this is doable using tuples, it's not so pretty.
var tuple = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9)); //and so on
or write your own tuple classes.
An interesting similarity to note is that both tuples and anonymous types give you immutability and equality comparability (both overrides Equals
and GetHashCode
) based on the properties by default.
Don't forget ValueTuple :)
Key Differences of the three:
Name | Access modifier | Type | Custom member name | Deconstruction support | Expression tree support |
---|---|---|---|---|---|
Anonymous types | internal | class | ✔️ | ❌ | ✔️ |
Tuple | public | class | ❌ | ❌ | ✔️ |
ValueTuple | public | struct | ✔️ | ✔️ | ❌ |
Source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/choosing-between-anonymous-and-tuple
精彩评论