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?
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.
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.
The ValueTuple types are mutable, whereas Tuple are read-only. Anonymous types can be used in expression trees, while tuples cannot.
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.
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
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