class foo {
public readonly int bar;
};
foo a = new foo() { bar = 123 };
error CS0191: A readonly field cannot be assigned to (except in a constructor or a variable initializer)
How can I assign bar in the object initializer above?
Can I initialize readonly members without having to write a custom constructor for every class/struct ?
is transformed by the compiler to
As you can see, the assignment to
baris neither in thefooconstructor nor a variable initializer.So the answer is: you can’t.