Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assign value of readonly variable in private method called only by constructors

Tags:

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.

like image 445
tom Avatar asked Jul 27 '11 17:07

tom


People also ask

Can readonly be set in constructor?

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.

How do you assign a value to readonly?

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.

Can readonly be initialized in constructor?

Readonly modifiers are initialized or are assigned values to them in constructor methods only.

Can we declare a readonly variable in a method?

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.


2 Answers

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";     } } 
like image 155
Zaid Masud Avatar answered Sep 21 '22 19:09

Zaid Masud


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();     } } 
like image 24
Antoine Aubry Avatar answered Sep 23 '22 19:09

Antoine Aubry