Why to access a value in an anonymous types, a compiler creates a getter method? Would not it be easier to give a direct access to read-only backing field?
2 Answers
Because properties of anonymous types are readonly after construction. You cannot change them once the object has been created.
They can achieve this using a get only property, but not with a public field (you can always change a field).
EDIT: I've looked around but couldn't find an obvious reason as to why they didn't go with public read-only fields. However, my best guess is: so that you can have properties.
If they had exposed public fields, and didn't have any properties, inevitably, anonymous types would be unusable by things that look for public properties, e.g. WPF binding. So having properties with private readonly backing fields probably was the safer choice.

- 38,383
- 7
- 71
- 92
-
2See [here](http://stackoverflow.com/questions/1089406/why-are-the-properties-of-anonymous-types-in-c-sharp-read-only). – Eren Ersönmez Nov 11 '13 at 08:42
-
The backing field is read-only and is initialized from the constructor. Can we change it without reflection? – user2341923 Nov 11 '13 at 08:42
-
After construction, you can't change a read-only field without using reflection. – Matthew Watson Nov 11 '13 at 08:53
-
Sorry, I missed that you mention read-only in the question. I will edit. – Eren Ersönmez Nov 11 '13 at 08:54
-
They can use a public readonly field to do this, however (which is what the OP is asking about). – Matthew Watson Nov 11 '13 at 09:02
It's not obvious why they don't simply use a read-only property, but a good reason is this:
If they just used a read-only property, you would know its name and therefore it would be easy to use reflection to change it.
Because they generate a private backing field, it's much harder to know what the name of it is (you'd have to inspect the generated IL), and therefore you are much less likely to change it using reflection. You still could, of course - but it would be such an obviously weird thing to do that you are definitely going to think once or twice before doing so.

- 104,400
- 10
- 158
- 276