Encapsulation is mechanism which allow hide some functionality within class or object to avoid its access from outside of that class or object.
Encapsulation is very useful in order to make protection for some operation and make them invoke in only one known place of code. Thanks to that we have easier control on such encapsulated properties or functions.
In order to define encapsulation we have protection levels which allow us make or prevent access to fields, properties and methods of our class.
C# has 4 levels of protection:
- private - fields can be used within objects of this class only. Default protection level in C#
- protected - fields can be used within objects of this class and in classes derived from this class
- public - fields can be used from any place in the code
- internal - this is new protection level and it is default protection level for classes. It means that class can be used by other classes within own assembly only. More about assemblies you can find here: Assembly unit
We defined 4 fields of different protection level (in points I, II, III, IV). Because our privateInt field is private we need to define two public accessible functions to set and get its value (getter (point V) and setter (point VI) - it is very common method of access to private fields keeping encapsulation).
Now take a look on point VII. We have not direct access to private values so direct assignment (as in commented line below point VII) is unavailable. In order to set value to private field we need to use our publicly accessible setter function.
The same situation is for getting value of private field (point VIII). We need to use public getPrivateInt() function in order to do that.
Of course if we were have access to protectedInt variable in above example we would also need to define publicly accessible getter and setter. It is because protected fields are accessible within class where are defined and within classes derived from class where protected fields are defined.
Now take a look at point XI. We do not have compiler error here, because we are accessing our internalInt field from the same assembly where testObject class is defined.
One more important information about protection levels you can find in point X. What is protection level of defaultProtectedInt? Its protection level is 'private'. It is because 'private' is default protection level for fields in C# (the same as in C++).
Above example you can download and compile from here:
https://github.com/xmementoit/CSharpAdventureExamples/tree/master/csharpBasics/protectionLevels
0 comments:
Post a Comment