Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does compiler generate different classes for anonymous types if the order of fields is different

I've considered 2 cases:

var a = new { a = 5 };
var b = new { a = 6 };
Console.WriteLine(a.GetType() == b.GetType()); // True

Ideone: http://ideone.com/F8QwHY

and:

var a = new { a = 5, b = 7 };
var b = new { b = 7, a = 6 };
Console.WriteLine(a.GetType() == b.GetType()); // False

Ideone: http://ideone.com/hDTcxX

The question is why does order of fields actually matter?

Is there any reason for this or it's just simply because it is (such is the design).

If the reason is just that anonymus types are not supposed to be used this way and you are not supposed to appeal to GetType, then why does compiler re-use a single class in first case and not just generate a new class for each anonymus type declaration?

like image 315
Artur Udod Avatar asked May 31 '13 14:05

Artur Udod


People also ask

What is the difference between an anonymous type and a regular data type?

From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.

When you define an anonymous type the compiler converts the type into?

Anonymous types are class type, directly derived from “System. Object” so they are reference types. If two or more Anonymous types have same properties in same order in a same assembly then compiler treats them as same type. All properties of anonymous types are read only.

Why anonymous types are preferred over tuples?

The ValueTuple types are mutable, whereas Tuple are read-only. Anonymous types can be used in expression trees, while tuples cannot.

Why we use anonymous types in c#?

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to explicitly define a type first. The type name is generated by the compiler and is not available at the source code level. The type of each property is inferred by the compiler.


1 Answers

So the reason for the design decision was ToString. An anonymous type returns a different string accoding to the order. Read Eric Lippert's blog.

{ a = 5, b = 7 }
{ b = 7, a = 6 }

Demo

like image 177
Tim Schmelter Avatar answered Sep 28 '22 21:09

Tim Schmelter