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 ?
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.
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.
You can initialize a ReadOnly property in the constructor or during object construction, but not after the object is constructed.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With