Is there a way to have a private readonly field in a class that could be assigned a value anywhere in the class, but only once??
That is, I am looking for a private read
You won't get compile time error, but you can accomplish what you're looking for with a property. In the setter, only set the value if an internal bool/flag is false. Once you set it the first time, set the flag to true. And if the setter is invoked again by another piece of code, you can throw an InvalidOperationException to let them know it has already been initialized
private bool fieldAlreadySet = false;
private string field;
public string Field
{
get {return field;}
set
{
if (fieldAlreadySet) throw new InvalidOperationException("field already set");
this.field = value;
fieldAlreadySet = true;
}
}