C# Encapsulation with Examples

Encapsulation is defined as the grouping of data into a single unit. It is a mechanism that links code and the data it manipulates. In a different way, encapsulation is a shield that prevents access to data from codes outside that shield.

  • Technically, class variables or data, when encapsulated, are hidden from any other class and can only be obtained through the function of your class in which they are declared.
  • Like encapsulation, class data is hidden from other classes and is therefore also called data holes.
  • Encapsulation is possible by Declaring all class variables private and assigning and retrieving variable values ​​from C # class attributes.

Example:

using System;

public class Encap
{
    private String studentName;
    private int studentAge;

    public string StudentName { get => studentName; set => studentName = value; }
    public int StudentAge { get => studentAge; set => studentAge = value; }
}
class GFG
{
    static public void Main()
    {
        Encap obj = new Encap();
        obj.StudentName = "shahzad";
        obj.StudentAge = 27;
        Console.WriteLine("Name: " + obj.StudentName);
        Console.WriteLine("Age: " + obj.StudentAge);
    }
}

Output:

Name: shahzad
Age: 27