Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Readonly field in object initializer

Tags:

c#

readonly

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 ?

like image 740
HerpDerpington Avatar asked Aug 22 '13 15:08

HerpDerpington


People also ask

Can we initialize readonly in C#?

To create a read-only field, use the readonly keyword in the definition. In the case of a field member, you get only one chance to initialize the field with a value, and that is when you call the class constructor. Beyond that, you'll would get an error for such attempt.

What is a readonly field?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

Can readonly be set in constructor?

You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.

How do you make a field read only in C#?

In C#, a readonly keyword is a modifier which is used in the following ways: 1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class.


1 Answers

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)

like image 154
Habib Avatar answered Sep 29 '22 20:09

Habib