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?
According to this page, the CLR default-constructs the object first before processing the initializer list, and you are therefore assigning to
bar
twice (once on default construction, once when the initializer is processed).Because an initializer is equivalent to
It is a rewrite behind the scenes.
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.
Again, I'm aware this doesn't solve the readonly issue as identified (and solved) above.
Allowing a
readonly
to be set in an initializer introduces contradictions and complications that can't be enforced at compile-time. I imagine the restriction is to avoid ambiguity. The big key is compile-time validation.Imagine this:
Now, consider:
Imagine that both of the above cases are unified (say, "by compiler magic"), however, enter in generics:
I believe the cases I have outlined show some complications of using a "dynamic"
readonly
approach and, at the end of the day, I believe it is merely a chosen language restriction (compilers implement languages) to enforce/allow compile-time validation.