Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Encapsulation | OOP Principles
C# Beyond Basics
course content

Course Content

C# Beyond Basics

C# Beyond Basics

1. Additional Structures & File Handling
2. Structs & Enumerators
3. Introduction to Object-Oriented Programming (OOP)
4. OOP Essentials
5. OOP Principles

Encapsulation

Encapsulation is essentially just a method of data organization. It involves organizing data and methods in the forms of classes so the whole program is essentially just based around classes and the data and methods are encapsulated within those classes. This encapsulation provides a way to control access to the internal state of an object, promoting modularity, maintainability, and security in a software system.

In Encapsulation, we use the Access Modifiers like public, private and protected to hide all most of the fields and methods of a class and expose only the ones that are needed to be used from outside.

Since most of the data is directly inaccessible outside the class, we use getters and setters to access or modify the data.

One good example is a Customer class which defines the customer of a bank:

cs

index

copy
1234567891011121314151617181920212223242526272829303132
public class Customer { private double accountBalance; private string customerName; private int pinCode; public Customer(double accountBalance, string customerName, int pinCode) { this.accountBalance = accountBalance; this.customerName = customerName; this.pinCode = pinCode; } public double getBalance(int pinCode) { if (pinCode == this.pinCode) return this.accountBalance; return } public void Deposit(double amount, int pinCode) { if(pinCode == this.pinCode) accountBalance += amount; } public void Withdraw(double amount, int pinCode) { if(pinCode == this.pinCode) accountBalance -= amount; } }

In the above example, no field is directly accessible or modifiable from outside. Instead we use methods like Deposit and Withdraw to modify the value whenever needed. Similarly to access the value of the balance we use the getBalance method.

The public keyword is generally discouraged to be used unless necessary.

1. What role do access modifiers play in encapsulation in C#?
2. Which of the following format specifiers should to used to a minimal amount to ensure Encapsulation?

What role do access modifiers play in encapsulation in C#?

Select the correct answer

Which of the following format specifiers should to used to a minimal amount to ensure Encapsulation?

Select the correct answer

Everything was clear?

Section 5. Chapter 6
We're sorry to hear that something went wrong. What happened?
some-alt