Artur Udod
Artur Udod

Reputation: 4753

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?

Upvotes: 12

Views: 304

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460228

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

Upvotes: 7

Justin Niessner
Justin Niessner

Reputation: 245459

You lead on to what I'm guessing the reason is: the types are anonymous so depending on GetType() to return reliable results is a terrible idea.

As for why the compiler re-uses a type if the order matches, I'm guessing it's simply to save time and space. When you take order into account, it's far easier to cache generated classes during compilation and then re-use them when needed.

Upvotes: 4

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

C# language specification, section 7.6.10.6, requires the sequence of properties to be the same in order for the anonymous types to be considered identical:

Within the same program, two anonymous object initializers that specify a sequence of properties of the same names and compile-time types in the same order will produce instances of the same anonymous type.

In your second example, the first anonymous class has the sequence of properties {a, b}, while the second anonymous class has the sequence {b, a}. These sequences are not considered to be the same.

Upvotes: 7

Related Questions