C# - Protection of field modification

C# provide two field modifiers for protection of field modification. Except of const keyword well-known from C++ we have additional readonly keyword in C#.
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
Now let's see on trying of modification our fields inside non-constructor public method:
  • 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
Code of this example you can download and check from here: https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/fieldPropertyDifference

0 comments:

Post a Comment

Powered by Blogger.

Sample Text

Sample Text

Sample text

Sample Text

Social Icons

Social Icons

Followers

Featured Posts