How do I assign a readonly member variable in an object initializer?
foo a = new foo() { bar = 123 };
is transformed by the compiler to
foo temp = new foo();
temp.bar = 123;
foo a = temp;
As you can see, the assignment to bar
is neither in the foo
constructor nor a variable initializer.
So the answer is: you can't.
To summarize the sentiment of the other answers: The error message isn't helpful— object initializers can't be used with readonly fields.
However, constructors with named arguments can, and the syntax to do so is quite similar. So similar you might even be thinking that you've seen C# object initializers for readonly fields (like I have been) when what you actually saw was this:
class Foo {
public Foo(int bar) {
this.bar = bar;
}
public readonly int bar;
};
Foo a = new Foo(bar: 123);
// instead of `new Foo() { bar = 123 };`