Getters, Setters and Properties

In this lesson, we will look into the getters, setters and properties in C#.

An Analogy

Consider the vending machine example. In this machine, there are several components working together at a micro level to make the vending machine functional at a macro level. There may be a display screen whose purpose is to provide an interface to the users. There may be a product dispenser whose purpose is to dispense products. There may be a cash collector whose purpose is to collect cash from the customers.

What we want to emphasize here is that there are many components providing their specific functionalities that don’t know each other’s internal implementation or working details. The screen doesn’t need to know how the cash collector component is internally keeping track of the total money collected until now, nor does the cash collector need to know how the screen is controlling its brightness.

While designing classes in OOP we follow a similar technique. Our classes should hide their internal implementation details and logic from the other classes. This is a very important concept called Encapsulation and we are going to explore it in detail in the upcoming chapter.

We already know that we declare fields in our classes. These fields actually represent the implementation details of our classes. In order to hide these from other classes, we need to declare them as private. The question here is “If all the fields should be private then how can we access and use these in our code in Main() or some other class?”

Getters and Setters

Getter and setter methods are the answer to the above question.

These two types of methods are very popular in OOP. A get method retrieves the value of a particular field, whereas a set method changes its value.

Get and set methods are implemented for fields that are declared private. It is considered a good practice to declare all the fields private.

While writing a getter or a setter method, it is a common convention to write the name of the corresponding field preceded by the Get or Set words, respectively.

Let’s write getter and setter methods for the count field in our VendingMachine class:

Get hands-on with 1200+ tech skills courses.