Skip to main content

Using Encapsulation with C# Code Example

 

Ziggy Rafiq Blog Post on C# Using Encapsultation

Overview

In this article, we are looking at Encapsulation as a fundamental concept in object-oriented programming that refers to the practice of hiding the internal workings of an object from the outside world. In this article, we will explore what encapsulation is, why it is important, how to implement it in C#, and the best practices for using it effectively. It's important to note that while we will be focusing on C# in this article, the principles of encapsulation can be applied to other programming languages, including Java, Python, TypeScript, and C++.


What is Encapsulation

Encapsulation is one of the fundamental concepts of object-oriented programming (OOP) that emphasizes the idea of data hiding. It refers to the bundling of data and methods that manipulate the data within a single unit or class, and restrict access to the internal state of the object from the outside world.

 In C#, encapsulation can be achieved using access modifiers such as public, private, protected, and internal. These modifiers define the level of accessibility to the members of a class.

Code Example of Using Encapsulation

In the example below, the BankAccount class has a private field balance that is not directly accessible from outside the class. Instead, it provides public methods Deposit, Withdraw, and GetBalance that allow external clients to manipulate the balance field indirectly. This way, the internal state of the object is protected from being modified or accessed by unauthorized clients.

Ziggy Rafiq Code Example of  Encapsulation using C#

Encapsulation not only provides security and protection to the object's internal state but also promotes modular programming by dividing the code into smaller, independent units or classes. It also allows for the implementation of the principle of information hiding, which states that only the relevant information should be exposed to the client while keeping the implementation details hidden.


Why use Encapsulation

Encapsulation is a fundamental principle of object-oriented programming (OOP) that is widely used in C# and other programming languages. Here are some reasons why we use encapsulation in C#.

  • Data Hiding: Encapsulation allows us to hide the implementation details and the internal state of an object from the outside world. By restricting access to the data members of a class, we prevent external clients from modifying the state of an object directly, which can lead to unexpected behaviour and errors.

  • Security: Encapsulation provides security to the object's data by limiting access to authorized clients only. By using access modifiers such as private, protected, and internal, we can control the level of access to the members of a class.

  • Modularity: Encapsulation promotes modular programming by dividing the code into smaller, independent units or classes. Each class encapsulates a set of related data and methods, which makes the code easier to maintain, test, and reuse.

  • Abstraction: Encapsulation is a key element of abstraction, which is the process of hiding unnecessary implementation details and exposing only the essential features to the client. By encapsulating the implementation details of a class, we can provide a simplified and abstract interface to the client, which reduces complexity and improves readability.

  • Code Flexibility: Encapsulation allows us to change the implementation of a class without affecting its external clients. By using access modifiers and other encapsulation techniques, we can modify the internal state and behaviour of a class without changing its public interface.

In nutshell a encapsulation is a powerful concept in C# that provides security, modularity, abstraction, and flexibility to the code. By using encapsulation, we can write better-structured, more maintainable, and more secure code.

How to use Encapsulation

Encapsulation in C# can be achieved by using access modifiers such as public, private, protected, and internal, which control the level of access to the members of a class. Here are some steps to use encapsulation in C#.

  • Declare Private Data Members: Declare the data members of a class as private to hide them from the outside world. Private members can be accessed only from within the same class.

 

  • Define Public Methods: Define public methods that allow external clients to access and manipulate the private data members indirectly. These methods should be used to set or get the values of the private data members.

 

  • Use Access Modifiers: Use access modifiers to control the level of access to the members of a class. The public methods that provide access to the private data members should be declared as public, while the private data members should be declared as private.

 

  • Implement Properties: Implement properties to encapsulate the private data members and provide a simplified interface to the client. Properties are a shorthand way of declaring getter and setter methods for a private data member.

Code Example of Encapsulation in C#

In the example below we have the Employee class that has three private data members: name, age, and salary. It also has three public properties: Name, Age, and Salary, which provide access to private data members. The get and set keywords are used to implement the getter and setter methods for each property.

Ziggy Rafiq Blog Post Code Example of Encapsulation in C#

Using encapsulation in this way provides several benefits.

  • The private data members of the Employee class are hidden from the outside world, which prevents external clients from modifying the state of an object directly.
  •  The public properties of the Employee class provide a simplified and abstract interface to the client, which reduces complexity and improves readability.
  • The access modifiers used in the Employee class control the level of access to the members of the class, which enhances security and prevents unauthorized access to the data.


Best Practice to use Encapsulation

There are a few best practices to use encapsulation in C#, which are as following below.

  • Use private access modifiers for data members: Declare the data members of a class as private to hide them from the outside world. This prevents external clients from accessing or modifying the internal state of an object directly.
  •  Use public properties for data access: Implement public properties to provide a simplified and abstract interface to the client. Properties encapsulate the private data members and provide a way to get or set their values indirectly.
  •  Use read-only fields for immutable data: If a data member is intended to be immutable, use the read-only keyword to prevent its value from being modified after initialization.
  •  Use access modifiers to control visibility: Use access modifiers such as public, private, protected, and internal to control the level of access to the members of a class. Only expose the members that need to be accessed by external clients.
  • Avoid exposing internal data: Avoid exposing internal data by using public methods to manipulate the internal state of an object. This prevents external clients from accessing or modifying the internal data directly.
  • Validate input parameters: Validate input parameters in public methods to ensure that the values passed by external clients are valid and do not violate the constraints of the class.
  • Use interfaces for abstraction: Use interfaces to provide a high-level abstraction of a class and to decouple the class from its clients. Interfaces provide a way to specify a contract that a class must implement without revealing its internal details.

By following these best practices, you can create well-encapsulated classes that are easy to use, maintain, and extend. Encapsulation promotes modularity, security, and flexibility, which are essential for writing high-quality software.


Comments

Most Viewed Ziggy Rafiq Blog Posts

A Complete Guide to Using GUIDs in C# with Code Examples

  Overview In this post, we are looking at GUIDs (Globally Unique Identifiers), which are widely used in C# for generating unique identifiers for objects, entities, and resources in a system. In this post, we'll explore the basics of GUIDs in C#, their advantages, and how to convert strings to GUIDs. In this post, we have used Guid Generator to create the GUID from the following URL Address https://guidgenerator.com/ What is GUID GUID (Globally Unique Identifier) in C# is a 128-bit value that is used to identify objects, entities, or resources in a unique manner across different systems and applications. It is also known as UUID (Universally Unique Identifier) in some other programming languages.   GUIDs are generated using a combination of unique factors such as the MAC address of the network adapter, the current time and date, and a random number. The resulting GUID is a string of 32 hexadecimal digits separated by hyphens, such as "b86f2096-237a-4059-8329-1bbcea72769b...

Primitives Data Types and None-Primitives Data Types in C# with Code Examples

  Overview I wrote this post to provide an explanation of primitive and non-primitive data types in C#. C# is a strongly typed programming language, where each variable and expression must have a specific data type. C# data types are categorized into two primary groups: primitive data types and non-primitive data types. Primitive data types are the simplest data types available in programming languages. They are typically pre-defined data types and can represent a single value, such as a boolean value, character, or integer. Examples of primitive data types include int, char, float, double, and boolean, which are common in programming languages like C++, C, and Java. Non-primitive data types are also referred to as composite data types or reference data types. They are constructed from primitive data types and are more complex than primitive data types. Non-primitive data types can hold multiple values and allow for the creation of more intricate data structures like tables, li...

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6

How to use Enum Data Values with .Net 6.0 Framework and Entity Framework Core 6 Overview An Enum (Enumeration) is a group of constants that are read-only value types. By default, the first value of the Enum variable is 0 i.e. Here we will create an Enum of Priorities type with read-only values of Highest, Normal and Low. We will set the read-only values using an integer assigning a number next to the value. By default, the integer value will start with 0. Here we will be assigning the integer value next to the Enum value such as in the below example and we will use a comma (,) to separate the item in the list of Enum(Enumeration).  We create Enum by using the Enum keyword and then using class, interface, and abstract. The reason we use an Enum is to ensure we improve our application performance and improve application readability, and maintainability, and reduces the complexity of the application hence why if you take a look at the example below of Status (NotStarted, Started, Comp...