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.
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";
}
}