Encapsulation -Protecting Data (C#)

Patel Dhiren
2 min readMay 25, 2023

--

Encapsulation is another fundamental concept in object-oriented programming (OOP) that allows you to wrapping the data (variables) and code acting on the data (methods) together as a single unit (class) .Hiding data by specifying accessibility for properties and methods.

Let’s continue with the example of a laptop to illustrate encapsulation in C#:

class Laptop
{
private string brand;
private string model;

public Laptop(string brand, string model)
{
this.brand = brand;
this.model = model;
}

public void PowerOn()
{
Console.WriteLine("The laptop is powering on...");
}

public void PowerOff()
{
Console.WriteLine("The laptop is powering off...");
}

public void PressPowerButton()
{
Console.WriteLine("Power button pressed.");
// Logic for power button functionality
}

public void UseKeyboard()
{
Console.WriteLine("Using the keyboard.");
// Logic for keyboard functionality
}

public void UseTouchpad()
{
Console.WriteLine("Using the touchpad.");
// Logic for touchpad functionality
}

// Other user-accessible features and methods
}

class Program
{
static void Main(string[] args)
{
Laptop laptop = new Laptop("Dell", "XPS 13");
laptop.PowerOn();
laptop.UseKeyboard();
laptop.UseTouchpad();
laptop.PressPowerButton();
laptop.PowerOff();
}
}

In this updated example, we have a Laptop class that encapsulates the laptop functionality and user-accessible features. The private fields brand and model store the brand and model information internally.

The public methods PowerOn(), PowerOff(), PressPowerButton(), UseKeyboard(), and UseTouchpad() represent the user-accessible features of the laptop. These methods expose the functionality of powering on/off the laptop, pressing the power button, and using the keyboard and touchpad, respectively. Inside these methods, you can include the specific logic for each feature.

In the Main method, we create an instance of the Laptop class, passing the brand and model as parameters. We then demonstrate the usage of the user-accessible features by calling the corresponding methods.

Thank you! I’m glad to hear that you’re enjoying the learning process. If you have any more questions or need further assistance, feel free to ask. Happy learning to you too!

--

--