Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top