Search code examples
c#readonly

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 ?


Solution

  • 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)