How does C# set a read-only property on anonymous object initialization

685 Views Asked by At

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?

3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

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.

1
On

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...