Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » Encapsulation in C#

Encapsulation in C#

In Object Oriented programming Encapsulation is the first pace. Encapsulation is the procedure of covering up of data and functions into a single unit (called class).

Author Rank :
Page Views : 69909
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

INTRODUCTION:

The object oriented programming will give the impression very unnatural to a programmer with a lot of procedural programming experience. In Object Oriented programming Encapsulation is the first pace. Encapsulation is the procedure of covering up of data and functions into a single unit (called class). An encapsulated object is often called an abstract data type. In this article let us see about it in a detailed manner.

NEED FOR ENCAPSULATION:

The need of encapsulation is to protect or prevent the code (data) from accidental corruption due to the silly little errors that we are all prone to make. In Object oriented programming data is treated as a critical element in the program development and data is packed closely to the functions that operate on it and protects it from accidental modification from outside functions.

Encapsulation provides a way to protect data from accidental corruption. Rather than defining the data in the form of public, we can declare those fields as private. The Private data are manipulated indirectly by two ways. Let us see some example programs in C# to demonstrate Encapsulation by those two methods. The first method is using a pair of conventional accessor and mutator methods. Another one method is using a named property. Whatever be the method our aim is to use the data with out any damage or change.

ENCAPSULATION USING ACCESSORS AND MUTATORS:

Let us see an example of Department class. To manipulate the data in that class (String departname) we define an accessor (get method) and mutator (set method).

using system;
public class Department
{
private string departname;
.......
// Accessor.
public string GetDepartname()
{
return departname;
}
// Mutator.
public void SetDepartname( string a)
{
departname=a;
}
}


Like the above way we can protect the private data from the outside world. Here we use two separate methods to assign and get the required data.

public static int Main(string[] args)
{
Department d =
new Department();
d.SetDepartname("ELECTRONICS");
Console.WriteLine("The Department is :"+d.GetDepartname());
return 0;
}

In the above example we can't access the private data departname from an object instance. We manipulate the data only using those two methods.

ENCAPSULATION USING PROPERTIES:

Properties are a new language feature introduced with C#. Only a few languages support this property. Properties in C# helps in protect a field in a class by reading and writing to it. The first method itself is good but Encapsulation can be accomplished much smoother with properties.

Now let's see an example.

using system;
public class Department
{
private string departname;
public string Departname
{
get
{
return departname;
}
set
{
departname=
value;
}
}
}
public class Departmentmain
{
public static int Main(string[] args)
{
Department d=
new Department();
d.departname="Communication";
Console.WriteLine("The Department is :{0}",d.Departname);
return 0;
}
}

From the above example we see the usage of Encapsulation by using properties. The property has two accessor get and set. The get accessor returns the value of the some property field. The set accessor sets the value of the some property field with the contents of "value". Properties can be made read-only. This is accomplished by having only a get accessor in the property implementation.

READ ONLY PROPERTY:

using system;
public class ReadDepartment
{
private string departname;
public ReadDepartment(string avalue)
{
departname=avalue;
}
public string Departname
{
get
{
return departname;
}
}
}
public class ReadDepartmain
{
public static int Main(string[] args)
{
ReadDepartment d=
new ReadDepartment("COMPUTERSCIENCE");
Console.WriteLine("The Department is: {0}",d.Departname);
return 0;
}
}

In the above example we see how to implement a read-only property. The class ReadDepartment has a Departname property that only implements a get accessor. It leaves out the set accessor. This particular class has a constructor, which accepts a string parameter. The Main method of the ReadDepartmain class creates a new object named d. The instantiation of the d object uses the constructor of the ReadDepartment that takes a string parameter. Since the above program is read-only, we cannot set the value to the field departname and we only read or get the value of the data from the field. Properties can be made also Write-only. This is accomplished by having only a set accessor in the property implementation.

WRITE ONLY PROPERTY:

using system;
public class WriteDepartment
{
private string departname;
public string Departname
{
set
{
departname=
value;
Console.WriteLine("The Department is :{0}",departname);
}
}
}
public class WriteDepartmain
{
public static int Main(string[] args)
{
WriteDepartment d=
new WriteDepartment();
d.departname="COMPUTERSCIENCE";
return 0;
}
}

In the above example we see how to implement a Write-only property. The class WriteDepartment has now has a Departname property that only implements a set accessor. It leaves out the get accessor. The set accessor method is varied a little by it prints the value of the departname after it is assigned.

CONCLUSION:

The Encapsulation is the first footstep towards the object-oriented programming. This article gives you a little bit information about Encapsulation. Using accessor and mutator methods we can make encapsulation. Another one method is using a named property. The benefit of properties is that the users of your objects are able to manipulate the internal data point using a single named item.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
G Gnana Arun Ganesh
G.GNANA ARUN GANESH, an ECE graduate (1997-2001) seeking a profession in either Software or Hardware Company. During Campus interview selected as a Software Engineer at GREEN MICRO SYSTEMS Chennai, a German collaboration company. Due to down stream in software market they have cancelled the offer. His skills includes VB, COM/DCOM, ASP, VB.NET, C# and Embedded systems. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
nice article by Ravi On September 16, 2007
Good stuff for beginners.
Reply | Email | Modify 
Good by raghav On November 1, 2008
Good Article
Reply | Email | Modify 
bb by om On November 5, 2008
bn mn
Reply | Email | Modify 
Good by sathya On March 19, 2009
Good Article
Reply | Email | Modify 
short and crispy by sathya On December 7, 2010
short and crispy, nice one for beginners
Reply | Email | Modify 
Nice Article! by Jitendra On April 23, 2011
This the best article I have ever seen, which have good definition and examples to explain encapsulation.
Reply | Email | Modify 
Nice.. by Gobi On June 28, 2011
Nice Article...
Reply | Email | Modify 
typo by Joey On November 16, 2011
Where you have d.departname="COMPUTERSCIENCE"; it actually should be "d.Departname" as that is the function you are calling. You are calling a private variable "departname" which can't be accessed.
Reply | Email | Modify 
Feedback by Sachin Sindhu by sachin On January 18, 2012
This is very nice article on encapsulation.Its explained in very simple and easy way.Thanks
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.