Search⌘ K

Getters, Setters and Properties

Explore how getters setters and properties help manage controlled access to private fields within C# classes. Understand the role of encapsulation and how to use these methods and property syntax to maintain your code's safety and readability while working with object-oriented programming concepts.

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 ...