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

tom picture tom · Jul 27, 2011 · Viewed 14.4k times · Source

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.

Answer

Zaid Masud picture Zaid Masud · Aug 22, 2012

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