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

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

提交回复
热议问题