HerpDerpington HerpDerpington - 7 months ago 45
C# Question

Readonly field in object initializer

I wonder why it is not possible to do the following:

struct TestStruct
public readonly object TestField;

TestStruct ts = new TestStruct {
/* TestField = "something" // Impossible */

Shouldn't the object initializer be able to set the value of the fields


Object Initializer internally uses a temporary object and then assign each value to the properties. Having a readonly field would break that.


TestStruct ts = new TestStruct 
     TestField = "something";

Would translate into

TestStruct ts;
var tmp = new TestStruct();
tmp.TestField = "something"; //this is not possible
ts = tmp;

(Here is the answer from Jon Skeet explaining the usage of temporary object with object initalizer but with a different scenario)