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

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

    The initializer is just syntactic sugar. When you write:

    new Foo { bar=0; };
    

    (Which, by the way, is a syntax error and should be this...)

    new Foo { bar=0 }
    

    what's actually happening is:

    var x = new Foo();
    x.bar = 0;
    

    Since the property is read-only, that second statement is invalid.

    Edit: Based on your edit, the question is a little unclear. A readonly property is, by design, not settable. It's built at object construction. This is enforced by both the compiler and the runtime. (Admittedly, I haven't tested the latter, since it would take some trickery to get around the former.)

    Keep in mind that there are two stages of "compilation." It's enforced when compiling the C# code into IL code, and it's enforced when compiling the IL code into machine code.

    It's not a technical limit of the CLR, and it's working exactly as it should, given the explicit readonly declaration. After the object is constructed, you can't set a readonly property.

提交回复
热议问题