3

In C#, object initializers can set public non-read-only fields and properties.

However, with anonymous types, the properties are read-only. So how does .NET set them on object initialization?

James McCormack
  • 9,217
  • 3
  • 47
  • 57

3 Answers3

7

Like all read-only properties, they can get set in the constructor.

A constructor for the anonymous type is generated with it and the fields set through it.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

The object initializer for anonymous types doesn't behave like a normal object initializer. i.e. it doesn't set the properties directly. It gets translated into a call to the constructor, which can change readonly fields.

CodesInChaos
  • 106,488
  • 23
  • 218
  • 262
1

Additionally they can be set via reflection or via patching of the managed code after creation.

E.g. just get the fields with the binding flags appropriate and then enumerate and call SetValue with the correct parameters...

Jay
  • 3,276
  • 1
  • 28
  • 38
  • 2
    They cannot. Properties in anonymous type are "true" read-only properties - they haven't setter at all. "Set backing field" and "set property" are different things. – Dennis May 18 '12 at 09:42