Does C# allow a variable that can\'t be modified? It\'s like a const
, but instead of having to assign it a value at declaration, the variable does not have any
You can roll your own using a custom setter (but don't use Object
unless you have to, choose the correct class):
private Object myObj = null;
private Boolean myObjSet = false;
public Object MyObj
{
get { return this.myObj; }
set
{
if (this.myObjSet) throw new InvalidOperationException("This value is read only");
this.myObj = value;
this.myObjSet = true;
}
}
EDIT:
This doesn't stop the private field being changed by the class internals.