1

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?

1 Answers1

4

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
}
David Pilkington
  • 13,528
  • 3
  • 41
  • 73
  • Stupid Question: Is that correct, when I call test(int a, int b) that this gets executed before (int a) gets called? – TheKrogrammer Oct 02 '17 at 07:48
  • @KenanTabinas The question is **not stupid**. And it has been asked several times on SO, for example [here](https://stackoverflow.com/q/4609774/982149). – Fildor Oct 02 '17 at 08:22
  • @Fildor This is not the correct answer. I asked an "Is that true question". An answer to a such a question is a boolean. In this example, the correct answer where be "no". But thanks anyway. – TheKrogrammer Oct 03 '17 at 11:57
  • @KenanTabinas Actually, it wasn't an answer to your question at all. I objected the statement of it being a stupid one and gave reference to a duplicate. – Fildor Oct 03 '17 at 19:49