C# compiler gave me the following error
CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
Do I have to move the code (in my private function) into the constructor? That sounds awkward.
Note that the private method was intended only to be called by the constructor. I expect that there is some sort of attribute that I can use to mark the method corresponding.
Yes. Have you tried constructor chaining as an alternative to using a common method?
You can literally paste "{ get; private set; }" in front of each equals sign in your readonly declarations to achieve almost the same thing (property can now be set in anywhere in class not just in constructor but at least its not changeable outside class). This is strictly true for value types but not reference types in which readonly might have an advantage.
Readonly field can only be assigned by the constructor. What you can do is to initialize the field with a method:
If you want to modify it you should not make it read only in the first place. Once a variable is read only you can modify it only in constructor or at declaration time as error suggests
According to MSDN
The
readonly
members can only assigned in the class level or on its constructor. that is the benefit from using thereadonly
keyword.You can use
readonly
as alternative to theconst
keyword when using classes "other that thestring
class", because the compiler will not allow you to assign aconst
to a classes.Despite what the other posts are saying, there is actually a (somewhat unusual) way to do this and actually assign the value in a method:
Example derived from here.
Alternatively, you can also return the value from a private method and assign it in the constructor as follows: