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.
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.
Readonly is a typescript keyword that makes the property read-only in a class, interface, or type alias. We make a property read-only by prefixing the property as readonly . We can assign a value to the readonly property only when initializing the object or within a constructor of the class.
Readonly modifiers are initialized or are assigned values to them in constructor methods only.
readonly fields cannot be defined within a method. const fields can be declared within a method. readonly variables are declared as instance variable and assigned values in constructor. const fields are to be assigned at the time of declaration.
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:
public class Foo { private readonly string _field; public Foo(string field) { Init(out _field, field); } private static void Init(out string assignTo, string value) { assignTo = value; } }
Example derived from here.
Alternatively, you can also return the value from a private method and assign it in the constructor as follows:
class Foo { private readonly string _field; public Foo() { _field = GetField(); } private string GetField() { return "MyFieldInitialization"; } }
Readonly field can only be assigned by the constructor. What you can do is to initialize the field with a method:
class Foo { private readonly Bar _bar = InitializeBar(); private Bar InitializeBar() { // Add whatever logic you need to obtain a Foo instance. return new Bar(); } }
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