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

后端 未结 10 1926
渐次进展
渐次进展 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条回答
  •  -上瘾入骨i
    2021-01-17 08:42

    This is a result of the implementation of the readonly keyword. The quote below is taken from the MSDN reference for readonly:

    The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

提交回复
热议问题