In c#, Encapsulation is a process of binding the data members and member functions into a single unit. In c#, the class is the real-time example for encapsulation because it will combine various types of data members and member functions into a single unit.
Generally, in c# the encapsulation is used to prevent alteration of code (data) accidentally from the outside functions. In c#, by defining the class fields with properties, we can protect the data from accidental corruption.
If we define class fields with properties, then the encapsulated class won’t allow us to access the fields directly. Instead, we need to use getter and setter functions to read or write data based on our requirements.
If you observe the above code, we defined variables with private access modifiers and exposed those variables in a public way using properties get and set accessors. If you want to make any modifications to the defined variables, then we can make it by using properties with get and set accessors.
Following is the example of defining an encapsulated class in c# programming language.
When you execute the above c# program, you will get the result as shown below.
This is how you can use encapsulation in the c# programming language to bind data members and member functions into a single unit by protecting the data from accidental corruption.