C# Encapsulation

Encapsulation is a mechanism in which we wrap the data into a single unit called class. By Encapsulation, Data alteration is not possible through unknown sources. The data can only be accessed through getter methods. Encapsulation increases the maintenance of the code which enhances usability. We can access the class data by the getter and setter methods only. We can't access the data directly. Let's see an example of encapsulation.

using System;  
namespace AccessSpecifiers  
{  
    class Employee  
    {  
        // Creating setter and getter for each property  
        public string ID { get; set; }  
        public string Name { get; set; }  
        public string Email { get; set; }  
    }  
}  
namespace AccessSpecifiers  
{  
    public class Program  
    {  
        public static void Main(string[] args)  
        {  
            Employee e= new Employee();  
            // Setting values to the properties  
            e.ID = "101";  
            e.Name = "Mohan Ram";  
            e.Email = "[email protected]";  
            // getting values  
            Console.WriteLine("ID = "+e.ID);  
            Console.WriteLine("Name = "+e.Name);  
            Console.WriteLine("Email = "+e.Email);  
        }  
    }  
}
Output
ID = 101
Name = Mohan Ram
Email = [email protected]



ADVERTISEMENT
ADVERTISEMENT