Pro Code Guide

Developer’s Guide To Programming


OOP Concept – Encapsulation in C# .NET

Updated Nov 30, 2020 | 0 comments

Encapsulation is one of the important building blocks in object-oriented programming. It is a mechanism in which data and code which manipulate this data are enclosed into a single unit. This unit can be a class in c# which allows the developer to hide data by making variables inaccessible outside class and providing functions, which can be accessed outside this class, to access these variables.

The idea is to hide the internals of an object behind specific methods i.e. restrict the direct access to some of an object’s component. In c# class, there are properties that allow class variables to be exposed by using get and set accessors.


As you can see in the above code, in class Employee private data member Name is exposed by using public property Name with set and get accessors. Set is used to change the value of data members and Get is used to read the value of data members. Also, validation rules if any can be implemented in the set method when the value is being changed to ensure that new value is within desired limits. This way you can control access to the internal state of the object.

In encapsulation one single unit i.e. class is formed with data members that store the current state of the object and method that can used to access these data members.

Access modifiers & access levels

Encapsulation is implemented by using access specifiers. All classes and class members can specify what access level they provide to other classes by using access modifiers. Only one modifier can be used per class, method & data members. An access specifier specifies the scope and visibility of class members.

publicThe type or member can be accessed by any other code in the same assembly or another assembly that references it.
privateThe type or member can only be accessed by code in the same class.
protectedThe type or member can only be accessed by code in the same class or in a derived class.
internalThe type or member can be accessed by any code in the same assembly, but not from another assembly.
protected internalThe type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.
private protectedThe type or member can be accessed by code in the same class or in a derived class within the base class assembly.
ASP.NET Core 5 Design Patterns: Thinking code using architectural principles, testing, design patterns, and C

Encapsulation – c# .NET example

Here is an example of an encapsulated class Employee in which we have specified properties Name & Total Experience to be specified by User. Employee Id is generated internally in class and generation logic is not exposed to the user and also user can only read Employee Id and cannot change it. Similarly, salary is also calculated internally in class, and the user can access employee salary by GetSalary method.

    class Employee
        private string name;
        private long id;
        private double yearsofexperience;

        public Employee()
            id = EmployeeService.GetEmployeeId();

        public long Id
            get { return id; }
        public string Name
            get { return name; }
            set { name = value; }
        public double YearsOfExperience
            get { return yearsofexperience; }
            set { yearsofexperience = value; }
        public double GetEmployeeSalary()
            double salary = 0;
            if (yearsofexperience == 0) salary = 50000;
            else if (yearsofexperience <= 5) salary = yearsofexperience * 100000;
            else if (yearsofexperience > 5) salary = yearsofexperience * 1.5 * 100000;

            return salary;

Newsletter Subscription

Stay updated! Instantly get notified about my new articles in your mailbox by subscribing via email

In below example, Employee class has been used and by specifying Name & Experience of Employee user is able to get Id & salary without worrying much about the internals of Employee class

    public partial class Form1 : Form
        public Form1()

        private void CreateEmployee()
            Employee employee = new Employee();
            employee.Name = txtEmployeeName.Text;
            employee.YearsOfExperience = Convert.ToInt32(txtEmployeeSalary.Text);

            txtEmployeeId.Text = employee.Id;
            txtEmployeeSalary.Text = employee.GetSalary().ToString();

        private void btnCreateEmployee_Click(object sender, EventArgs e)

Advantages of Encapsulation

  • The internal implementation of the class is hidden from the user of the class. The user is exposed to just specific methods of the class.
  • It provides control over the data by allowing developers based on their requirements to consciously provide set or get methods for a private data member.
  • It makes easier to perform unit testing of the class.


Encapsulation is a fundamental block of object-oriented programming and it prevents access to implementation details. Encapsulation enables the programmer to implement the desired requirement for the level of access to the internals of the object.

It not only allows the programmer to control which attributes can be accessed or modified but also allows to limit changes as per the requirements.


You can also check my another Article explaining ASP.NET Core caching –

Hope you found this article useful. Your support is appreciated!
Buy me a coffeeBuy me a coffee
Home 9 Programming 9 OOP Concept – Encapsulation in C# .NET

Set start URL in ASP.NET Core – Quick & Easy ways

This article will cover the ways to set start URL in ASP.NET Core 5 applications i.e. change the default URL (http://localhost:5000) in ASP.NET Core applications. When you create any new ASP.NET Core application whether its MVC App or Web API and run it then it will...

Hangfire in ASP.NET Core – Easy way to Schedule Background Jobs

This article covers detail about how to integrate Hangfire in ASP.NET Core applications which is an easy way to schedule background jobs in .NET Core and .NET based applications. Background jobs or tasks allow the programmers to execute code on a different thread but...

How to Send Emails in ASP.NET Core – Quick & Easy Guide

These days sending emails like user email id confirmation, OTP emails, acknowledgments, etc. is a very common requirement of any application. In this article, we will see a demo about how to send emails in ASP.NET Core in quick & easy steps. We will create an...

ML.NET – Machine Learning with .NET Core – Beginner’s Guide

This article will get you started with the fundamentals of Machine Learning and how to get started with Machine Learning with .NET Core i.e. ML.NET. We will even learn different concepts of Machine learning with a brief overview. Introduction to Machine Learning...

Implement Cookie Authentication in ASP.NET Core – Detailed Guide

This article will get you started with implementing cookie authentication in ASP.NET Core applications. Cookie authentication allows you to have your own login/register screens & custom logic for user-id/password validation without the need to use ASP.NET Core...

ASP.NET Core Identity Roles based Authorization

This article will get you started with what are ASP.NET Core Identity roles and the need for roles, how to enable ASP.NET Core Identity roles in MVC Application, and how to implement role-based authorization. Role-based authorization is for basic authorization where...

Dependency Injection in ASP.NET Core 3.1 – Beginner’s Guide

This article will cover in details dependency injection in ASP.NET Core 3.1. ASP.NET Core is designed from the ground up to support the dependency injection design pattern. Dependency injection in ASP.NET Core provides a technique to create applications that are...

Real-time Web Applications with SignalR in ASP.NET Core 3.1

In this article, we will learn about real-time web & how to build real-time web applications using SignalR in ASP.NET Core. As part of this article, we will work on an application that can send real-time messages/alerts to all connected users or private messages...

Code Profiling using MiniProfiler in ASP.NET Core 3.1

This article will get you started with how to enable miniprofiler in ASP.NET Core to measure the performance of your application. MiniProlifer helps you understand how your application is performing by allowing you to profile any part of code in ASP.NET Core...

Microservices with ASP.NET Core 3.1

Microservices is a type of Architecture in which application is created as multiple small independent serviceable components. This article will cover in detail how to create microservices with ASP.NET Core, Serilog, Swagger UI, Health Checks & Docker containers....


Submit a Comment

Your email address will not be published. Required fields are marked *