Search code examples
c#constructorinline

Call a method from constructor with "constructor rights"


I have a member. This member is only assigned by constructor, why I thought it could be made readonly. This very class has, several constructors.

Is there a way to assign this member once, to create a single point of failure.

First, I thought it could work with an inline method. The only way I found is with:

    [MethodImpl(MethodImplOptions.AggressiveInlining)]

But it doesn't work.

Or is it possible to give a method "constructor rights" or is it impossible to do this?


Solution

  • I think that your best bet here is to overload your constructors and then chain them

    readonly int myReadonly;
    
    public test(int a, int b) 
        :this (a)
    {
        myReadonly = b;
    }
    
    private test(int a) 
    {
        //other work
    }