Access Modifiers in C#
2016-07-29
Encapsulation
Encapsulation is a basic tenet of object-oriented programming that refers to the segregation of a portion of code to remove dependencies on an uncertain implementation. By uncertain, I mean that it may be prone to change.
A simplistic way to visualize encapsulation is to imagine, for instance, a machine in a factory that takes corn on the cob and returns shaved corn kernels. The actual shaving process may be done through method A or method B or any number of other methods. But since we have encapsulated the process of shaving kernels off the cob, the rest of our factory processes are not affected should we decide to switch between methods.
In the same way, if I am writing code that other components rely on, I want to minimize any risk of those components breaking should I need to alter my implementation in the future.
Access modifiers
“Access modifiers help us implement encapsulation.” — Ben S, Stack Overflow
Here below are the access modifiers present in C#, along with descriptions from the MSDN C# Programming Guide. I have interjected my own comments for each one in green font:
- public: The type or member can be accessed by any other code in the same assembly or another assembly that references it. Encapsulation is absent. Any class anywhere can access the code.
- private: The type or member can be accessed only by code in the same class or struct. The most restrictive access modifier, as it only allows local (same class) access.
- protected: The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class. Same as private, except subclasses of the current class are also allowed access.
- internal: The type or member can be accessed by any code in the same assembly1, but not from another assembly. Same as public, but only across code in the same assembly.
An additional access modifier derived from these is protected internal, which is similar to the internal access modifier except that it can also be accessed “from within a derived class in another assembly” (Access Modifiers, 2015).
By default, C# gives types and members the most restrictive access modifier available. Therefore, the snippets below are effectively the same:
class Animal
{
boolean isEndangered;
class Animal() {}
}
internal class Animal
{
private boolean isEndangered;
private class Animal() {}
}
For more details on Access Modifiers in C#, have a look at this guide from MSDN.
-----
Notes
- 1 An assembly is a piece of code generated by the .NET compiler upon compilation. On the first compilation, the assembly is generated. On subsequent compilations, the assembly is updated, not regenerated.