Current answer by @poke is correct and notes differences between tuple and anonymous types. I'm going to discuss why you would still use them or prefer one over another.
There are two new c# 7 features that retires anonymous types. ValueTuples and Records.
The main reason that you would not use anonymous types is
- you can not use anonymous types globally and they are only type safe when used locally. not being local you have to treat it as
dynamic
object which has significant performance overhead
Reasons that you prefer tuple over anonymous types.
they are type safe all over the place. (regardless of naming)
they can be used as method arguments, type arguments, field and pretty much every where. (yes I said pretty much, there are places that needs to adopt with tuples, its matter of time.)
since they can be used as type argument, you probably prefer to wrap lightweight set of parameters in single parameter. like Stack<(min, mid, max)>
you can change items naming when ever you feel its appropriate, in generic context name item
may satisfy and in more specific context you need more specific name too, like car
they are implicitly convertible, int, int
can be assigned to (int, long)
without explicit cast.
they are used in Deconstructs. which brings a lot of syntactic sugar to language.
you can have multiple assignments and declarations like (int x, int y) = (0, 1)
Having all of this features, there is still one reason that you may prefer anonymous type over tuple.
- Anonymous types are reference type but tuples are value type.
but what if you want to use anonymous type globally? do you prefer to have dynamic objects or statically typed objects?
The incoming Records feature again defeats anonymous types. with records you define your class in short, concise and convenient way. not a big deal. just a single line
public class Point(X, Y);
Type safety all over the place, and you also have reference type in hand. these two new features bring every thing to defeat anonymous types.
Note that Records are not added yet, we just have to wait.
Only remaining real usage of anonymous types will be
As I said ValueTuples are not compatible with every component yet. its just matter of time, but this is how its going to be like in future.
enough arguments. in my humble opinion usage of anonymous types becomes rare, old programmers may still use anonymous type in Linq by habit.
new {x, i}
makes it completely clear that it is a new object that is being returned, whereas I had to compare the two examples to figure out what the first one does. But then it might just be me. – Veer(x, i)
has unnamed tuple elements, but they're implicitly named in C# 7.1. – Vanderpooly => arr[i]
bey => arr[y.i]
? Also, tuples are used when the element names are not needed(1, 'a')
– Armlet