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

后端 未结 10 1925
渐次进展
渐次进展 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: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).

提交回复
热议问题