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 { bar=0; }; // does not work
Is this due to some technical limits of the CLR?
EDIT
I know that new Foo { bar=0; }
is the same as new Foo().bar=0;
, but is "readonly" enforced by the CLR, or is it just a compiler limitation?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With