HI WELCOME TO SIRIS

C# Encapsulation

Leave a Comment
Encapsulation is the concept of wrapping data into a single unit. It collects data members and member functions into a single unit called class. The purpose of encapsulation is to prevent alteration of data from outside. This data can only be accessed by getter functions of the class.
A fully encapsulated class has getter and setter functions that are used to read and write data. This class does not allow data access directly.
Here, we are creating an example in which we have a class that encapsulates properties and provides getter and setter functions.

Example

  1. namespace AccessSpecifiers  
  2. {  
  3.     class Student  
  4.     {  
  5.         // Creating setter and getter for each property  
  6.         public string ID { getset; }  
  7.         public string Name { getset; }  
  8.         public string Email { getset; }  
  9.     }  
  10. }  
  1. using System;  
  2. namespace AccessSpecifiers  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             Student student = new Student();  
  9.             // Setting values to the properties  
  10.             student.ID = "101";  
  11.             student.Name = "Mohan Ram";  
  12.             student.Email = "mohan@example.com";  
  13.             // getting values  
  14.             Console.WriteLine("ID = "+student.ID);  
  15.             Console.WriteLine("Name = "+student.Name);  
  16.             Console.WriteLine("Email = "+student.Email);  
  17.         }  
  18.     }  
  19. }  
Output:
ID = 101
Name = Mohan Ram
Email = mohan@example.com

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.