What are access modifiers? Access modifiers are used to control access to a class and/or its members. We use these to protect our programs. It is used for safety reasons.
Coders never want to introduce bugs in their code. Careful use of access modifiers will mitigate that risk.
There are five types of access modifiers in C#. In our discussion, we will start with the two extremes: public and private.
- Public
- Private
- Protected
- Internal
- Protected Internal
In object-oriented programming we have three major concepts:
- Encapsulation (information hiding)
- Inheritance
- Polymorphism
This post will introduce encapsulation. Inheritance and polymorphism will be for another post. Think about division of duties in a small company. Each has responsibilities. In OOP we have classes. Each class will be responsible for one thing. Everyone else in the company doesn’t deal with the details of everyone else. In our classes we want to encapsulate (hide) some data in our class with the use of some fields as well as some functionality (methods). Fields are the implementation details and they should be private/hidden from the outside world. To do this we can create a field in our class and use the private access modifier. This way, when code outside the class instantiates the class into an object in memory, it does not have access to our backing private field.
Since the _birthdate field is private, we cannot get access to it from the outside. This is an example of encapsulation.
Public
Here is an example of public, one modifier you use frequently. Public is accessible from anywhere.
public class Customer { public void Promote() { Console.WriteLine("promoting..."); } }
Below is how we consume it.
var cust = new Customer(); cust.Promote();
Private
Let’s look at some demonstration code. Notice that we name our classes with Pascal case and we prefix our private fields with the underscore, and we use Camel case for our private fields (_birthdate in this example). Pascal case sets the first letter of each word as upper case. Camel case sets the first letter of the first word as lower case and every other first letter of each word as upper case. Use pascal case for naming the class any any of its methods. Private fields start with an underline and use camel case. Parameters in our methods should use camel case.
There is an easier way to achieve this. It’s called Properties. That’s why I said that this code is for demonstration purposes.
class Program { public class Person { private DateTime _birthdate; public void SetBirthdate(DateTime birthdate) { // method _birthdate = birthdate; } public DateTime GetBirthdate() { return _birthdate; } } static void Main(string[] args) { var person = new Person(); person.SetBirthdate(new DateTime (1982, 1, 1)); Console.WriteLine("DOB is {0}", person.GetBirthdate()); Console.ReadKey(); } }