HerpDerpington HerpDerpington - 15 days ago 7
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
?

Answer

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

Following

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)

Comments