HerpDerpington HerpDerpington - 1 year ago 78
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 Source

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)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download