Encapsulation in C#: Hiding Data with Access Control

The Core Principles of OOP : 1- Encapsulation 💊 Encapsulation is a fundamental concept in Object-Oriented Programming (OOP). It refers to the practice of hiding internal data and controlling access to it through properties or methods. In C#, encapsulation is typically implemented using private fields and public properties. Instead of allowing direct access to a variable, we protect it and expose it through controlled accessors ("get" and "set"). This helps maintain data integrity, security, and cleaner code architecture. 📌 Example in C#: class Person { private string name; // Private field (hidden data) public string Name // Public property { get { return name; } // Read the value set { name = value; } // Modify the value } } In this example: - The variable name cannot be accessed directly from outside the class. - Access is controlled through the Name property. - This allows us to add validation or logic when getting or setting the value. 📌 Why Encapsulation Matters - Protects sensitive data - Prevents unintended modifications - Improves maintainability and scalability - Allows validation before updating values Example with validation: public string Name { get { return name; } set { if (!string.IsNullOrEmpty(value)) { name = value; } } } Here, the property ensures that the name cannot be set to an empty value. ✅ In short: Encapsulation means bundling data with the methods that control access to it, making your C# applications more secure, organized, and reliable. #CSharp #DotNet #Programming #OOP #SoftwareEngineering

  • graphical user interface

From OOP View -> Getters and setters are evil. https://www.yegor256.com/2016/04/05/printers-instead-of-getters.html The key idea of object-oriented programming is to hide data behind objects. This idea has a name: encapsulation. In OOP, data must not be visible. Objects must only have access to the data they encapsulate and never to the data encapsulated by other objects. https://www.yegor256.com/2016/07/06/data-transfer-object.html

To view or add a comment, sign in

Explore content categories