Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous type and tuple

What is the difference between anonymous type and tuple?

like image 704
Amutha Avatar asked Apr 10 '10 15:04

Amutha


People also ask

What are anonymous data types?

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.

Is tuple reference type?

Tuple types are reference types. System. ValueTuple types are mutable.

What is anonymous type of functions?

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.

What are difference between anonymous and dynamic types?

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.


2 Answers

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.

like image 95
Alex Dresko Avatar answered Sep 28 '22 03:09

Alex Dresko


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.

like image 36
Aaronaught Avatar answered Sep 28 '22 02:09

Aaronaught