What is the difference between anonymous type and tuple?
Anonymous types are class types that derive directly from object , and that cannot be cast to any type except object . The compiler provides a name for each anonymous type, although your application cannot access it.
Tuple types are reference types. System. ValueTuple types are mutable.
Definition. Anonymous type, as the name suggests is a type that doesn't have any name. Anonymous types are the new concept in C#3.0 that allow us to create new type without defining them. This is a way to define read only properties into a single object without having to define type explicitly.
Anonymous type is a class type that contain one or more read only properties whereas dynamic can be any type it may be any type integer, string, object or class. Anonymous types are assigned types by the compiler. Anonymous type is directly derived from System.
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.
void Main() { var result = Whatever((123, true)); Debug.Assert(result.Something == 123); Debug.Assert(result.Another == "True"); } (int Something, string Another) Whatever((int Neat, bool Cool) data) { return (data.Neat, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With