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 {
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.
Because an initializer is equivalent to
var foo = new Foo();
foo.bar=0;
It is a rewrite behind the scenes.
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).
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