How do I set a readonly field in an initialize method that gets called from the constructor?

Viewed 21726

I'm sure I've seen somewhere that I can do the following by using an attribute above my Init() method, that tells the compiler that the Init() method must only be called from the constructor, thus allowing the readonly field to be set. I forgot what the attribute is called though, and I can't seem to find it on google.

public class Class
{
    private readonly int readonlyField;

    public Class()
    {
        Init();
    }

    // Attribute here that tells the compiler that this method must be called only from a constructor
    private void Init()
    {
        readonlyField = 1;
    }
}
10 Answers

How about an initialized property with a getter only (as of C# 6.0)?

    private int MyProperty { get; } = 0;

I know this is late, but what about using a class as a return value instead of using out params if there is a need to initialize multiple fields, are there any drawacks? Imho this is more convenient and more readable than using nested constructors.

public class MyInitClass
{
    public int Field1 { get; set; }
    public int Field2 { get; set; }
}

public class Class
{
    private readonly int readonlyField1;
    private readonly int readonlyField2;

    public Class()
    {
        var init = Init();
        readonlyField1 = init.Field1;
        readonlyField2 = init.Field2;
    }

    private MyInitClass Init()
    {
        return new MyInitClass() { Field1 = 1, Field2 = 2 };
    }
}
Related