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

后端 未结 10 1909
渐次进展
渐次进展 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:33

    What you're trying to do is this:

       class Foo
       {
            public readonly int bar;
    
            Foo(int b)
            {
                 bar = b;  // readonly assignments only in constructor
            }
       }
    
       Foo x = new Foo(0);
    

提交回复
热议问题