Al Idian

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:

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