Professional Documents
Culture Documents
Encapsulation Is Defined 'As The Process of Enclosing One or More Items
Encapsulation Is Defined 'As The Process of Enclosing One or More Items
Public
Private
Protected
Internal
Protected internal
Technically in encapsulation, the variables or data of a class are
hidden from any other class and can be accessed only through any
member function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes,
so it is also known as data-hiding.
Encapsulation can be achieved by: Declaring all the variables in
the class as private and using C# Properties in the class to set and
get the values of variables.
using System;
using System.Text;
namespace Tutlane
{
class User
{
private string location;
private string name;
public string Location
{
get
{
return location;
}
set
{
location = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
}
class Program
{
static void Main(string[] args)
{
User u = new User();
// set accessor will invoke
u.Name = "Suresh Dasari";
// set accessor will invoke
u.Location = "Hyderabad";
// get accessor will invoke
Console.WriteLine("Name: " + u.Name);
// get accessor will invoke
Console.WriteLine("Location: " + u.Location);
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}
}