Why can't I initialize readonly variables in a initializer?

后端 未结 10 1922
渐次进展
渐次进展 2021-01-17 08:16

Why can\'t I initialize readonly variables in a initializer? The following doesn\'t work as it should:

class Foo
{
    public readonly int bar;
}

new Foo {          


        
相关标签:
10条回答
  • 2021-01-17 08:47

    I know this isn't a direct answer to the poster's question, but the newer version of C# now allows for direct initialization from the property itself as follows.

    public int bar { get; set; } = 0;
    

    Again, I'm aware this doesn't solve the readonly issue as identified (and solved) above.

    0 讨论(0)
  • 2021-01-17 08:48

    Because an initializer is equivalent to

    var foo = new Foo();
    foo.bar=0;
    

    It is a rewrite behind the scenes.

    0 讨论(0)
  • 2021-01-17 08:51

    According to this page, the CLR default-constructs the object first before processing the initializer list, and you are therefore assigning to bar twice (once on default construction, once when the initializer is processed).

    0 讨论(0)
  • 2021-01-17 08:54

    There is not much wrong in your code or assumptions with the exception maybe that it is an important feature of initializer lists to impose no sequence constraints (especially true for C++). The semicolon is a sequencing operator, consequently initializer lists are comma separated instead.

    Unless you argue that specifications are correct by definition I believe that the language specification is wrong here. It partly breaks an important feature of the language which is the notion of readonly. The ambiguity problems mentioned in other answers have in my opinion one single underlying cause. Readonly is a very intrusive feature and going half way regarding const correctness is difficult to get right and more importantly, harmful to coding styles developed.

    What you are looking for and probably found in the meantime are named arguments: https://stackoverflow.com/a/21273185/2712726 It is not what you asked for but gets near.

    Also to be fair, I must add that there are very knowledgeable authors who will totally disagree with these views on const correctness that C++ developers often have. Eric Lippert, who admittedly has brilliant posts has written this (horrifying to C++ developers) statement: https://stackoverflow.com/a/3266579/2712726

    0 讨论(0)
提交回复
热议问题