❔ what's a usecase where "readonly" would be prefered to property with an init setter?
init can be used in both constructor and in object initializers. readonly only in constructor.
6 Replies
Fields are usually declared as private / protected while properties are generally the opposite. A property like:
can be modified to include some additional processing when fetching the underlying string set initially
like:
A potential issue with the case above is, it results in a new string allocation each time the property is called.
You could also do
I would also like to note that for Dependency Injection,
readonly
is used a lot for injected objects,
eg.
Also, depending on the placement of the field (I believe) the value of the field is set before the constructor is invoked and works like a static context.arion
REPL Result: Success
Console Output
Compile: 672.859ms | Execution: 79.615ms | React with ❌ to remove this embed.
Looks like the readonly fields are initialized first then the constructor
If you do initialize a readonly field from the constructor, thats also do-able
it would be prefered if you're using a field and not a property
because they are different things for different kinds of members
if you take the rule "don't expose fields publicly" and apply it here that answers your question
okay, readonly fields for class-wide manipulation
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.