So we have three levels of field modification protection in C#:
- private bool fieldName - such field cannot be modify outside class but can be modify inside
- private readonly bool fieldName - such field can be modified in constructor of class only (useful for variables which should be once initialized and not modified later. In terms of properties - readonly properties can never be modified.
- private const bool fieldName - such field can never be modified
See how those modifiers are working on the example below:
In points I, II, III we are defining fields with different modification protection levels. In points IV we have constructor of our TestClass and in point VIa we have one additional function for modification values of our fields.
First lets's analyze constructor modifications.
- point V - we have modificableField which has not any modification protection. So it can be modify anywhere within class - also in constructor. No compilation error.
- point VI - readonly protected field - it can be modify within constructor only - we are within constructor - no compilation error
- point VII - const protected field - it cannot be modify anywhere - if you uncomment that line you will receive compilation error because you are trying modify field which is immutable
- point VIII - the same situation as in point V - we can modify this field - no compilation error
- point IX - readonly protected field and we are outside of constructor, so we cannot modify this field - compilation error when you uncomment this line
- point X - const field - the same situation as in point VII - compilation error when you uncomment this line
0 comments:
Post a Comment