You pass the value in on the constructor:
public class foo
{
public readonly int _bar;
public foo(int bar)
{
_bar = bar;
}
};
var x = new foo(12345);
What the compiler is telling you is that the only place you can set your readonly field is in the constructor of the class that holds it, this means:
- if you need it to change during the lifetime of the object then
readonly
is not the correct option to use
- if each instance of the class needs to hold a custom value in the readonly member variable then you need to inject it as part of the constructor
I would suggest that it isn't a good practice to make your readonly field public like this, instead just expose it as a public property that only has a getter.