Blue Theme Orange Theme Green Theme Red Theme
 
DevExpress Free UI Controls
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 » Understanding Properties in C#

Understanding Properties in C#

In C#, properties are nothing but natural extension of data fields. They are usually known as 'smart fields' in C# community.

Author Rank :
Page Views : 578335
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

In C#, properties are nothing but natural extension of data fields. They are usually known as 'smart fields' in C# community. We know that data encapsulation and hiding are the two fundamental characteristics of any object oriented programming language.In C#, data encapsulation is possible through either classes or structures. By using various access modifiers like private, public, protected, internal etc it is possible to control the accessibility of the class members. 

Usually inside a class, we declare a data field as private and will provide a set of public SET and GET methods to access the data fields. This is a good programming practice, since the data fields are not directly accessible out side the class. We must use the set/get methods to access the data fields. 

An example, which uses a set of set/get methods, is shown below. 

//SET/GET methods
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private int x;
public void SetX(int i)
{
x = i;
}
public int GetX()
{
return x;
}
}
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();
mc.SetX(10);
int xVal = mc.GetX();
Console.WriteLine(xVal);
//Displays 10
}
}

But C# provides a built in mechanism called properties to do the above. In C#, properties are defined using the property declaration syntax. The general form of declaring a property is as follows.          

<acces_modifier> <return_type> <property_name>
{
get
{
}
set
{
}
}

Where <access_modifier> can be private, public, protected or internal. The <return_type> can be any valid C# type. Note that the first part of the syntax looks quite similar to a field declaration and second part consists of a get accessor and a set accessor. 

For example the above program can be modifies with a property X as follows.      

class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x =
value;
}
}
}

The object of the class MyClass can access the property X as follows.

MyClass mc = new MyClass();

mc.X = 10; // calls set accessor of the property X, and pass 10 as value of the standard field 'value'.
This is used for setting value for the data member x.
Console.WriteLine(mc.X);// displays 10. Calls the get accessor of the property X. 

The complete program is shown below. 

//C#: Property
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x =
value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc =
new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);
//Displays 10
}

 
Remember that a property should have at least one accessor, either set or get. The set accessor has a free variable available in it called value, which gets created automatically by the compiler. We can't declare any variable with the name value inside the set accessor.

We can do very complicated calculations inside the set or get accessor. Even they can throw exceptions. 

Since normal data fields and properties are stored in the same memory space, in C#, it is not possible to declare a field and property with the same name. 

Static Properties

C# also supports static properties, which belongs to the class rather than to the objects of the class. All the rules applicable to a static member are applicable to static properties also. 

The following program shows a class with a static property. 

//C# : static Property
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private static int x;
public static int X
{
get
{
return x;
}
set
{
x =
value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass.X = 10;
int xVal = MyClass.X;
Console.WriteLine(xVal);
//Displays 10
}
 

Remember that set/get accessor of static property can access only other static members of the class. Also static properties are invoking by using the class name. 

Properties & Inheritance 

The properties of a Base class can be inherited to a Derived class. 

//C# : Property : Inheritance
//Author: rajeshvs@msn.com
using System;
class Base
{
public int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
}
class MyClient
{
public static void Main()
{
Derived d1 =
new Derived();
d1.X = 10;
Console.WriteLine(d1.X);
//Displays 'Base SET Base GET 10'
}
}

The above program is very straightforward. The inheritance of properties is just like inheritance any other member. 

Properties & Polymorphism 

A Base class property can be polymorphicaly overridden in a Derived class. But remember that the modifiers like virtual, override etc are using at property level, not at accessor level. 

//C# : Property : Polymorphism
//Author: rajeshvs@msn.com
using System;
class Base
{
public virtual int X
{
get
{
Console.Write("Base GET");
return 10;
}
set
{
Console.Write("Base SET");
}
}
}
class Derived : Base
{
public override int X
{
get
{
Console.Write("Derived GET");
return 10;
}
set
{
Console.Write("Derived SET");
}
}
}
class MyClient
{
public static void Main()
{
Base b1 =
new Derived();
b1.X = 10;
Console.WriteLine(b1.X);
//Displays 'Derived SET Derived GET 10'
}
}

Abstract Properties
 

A property inside a class can be declared as abstract by using the keyword abstract. Remember that an abstract property in a class carries no code at all. The get/set accessors are simply represented with a semicolon. In the derived class we must implement both set and get assessors. 

If the abstract class contains only set accessor, we can implement only set in the derived class. 

The following program shows an abstract property in action. 

//C# : Property : Abstract
//Author: rajeshvs@msn.com
using System;
abstract class Abstract
{
public abstract int X
{
get;
set;
}
}
class Concrete : Abstract
{
public override int X
{
get
{
Console.Write(" GET");
return 10;
}
set
{
Console.Write(" SET");
}
}
}
class MyClient
{
public static void Main()
{
Concrete c1 =
new Concrete();
c1.X = 10;
Console.WriteLine(c1.X);
//Displays 'SET GET 10'
}


The properties are an important features added in language level inside C#. They are very useful in GUI programming. Remember that the compiler actually generates the appropriate getter and setter methods when it parses the C# property syntax.

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
 
Rajesh VS
Rajesh V.S is a software engineer in the area of C/C++/JAVA for the last 5 years. Currently he is interested in core C# language. He is Sun Certified Java Programmer. His other area of interest includes Design Patterns and CORBA. 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 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. 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:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Properties in C# by Manoj On September 6, 2007
What is the Properties. How is it useful for us. Can we have any alternative in it's place.
Reply | Email | Modify 
Thanks by Nandu On January 21, 2008
Thank you very much for your Explanation.
Reply | Email | Modify 
ty by aniket On November 16, 2008
ty
Reply | Email | Modify 
doubt by bharani On February 21, 2009
private int x; public int X { get { return x; } set { x = value; } what is the necessary to declare the variable x as a private and public? could u plz explain me?
Reply | Email | Modify 
doubt by sethu On March 30, 2009
how to get the value of datagridview
Reply | Email | Modify 
Have a look for Proporties and other C# concepts by Subhendu On June 16, 2010
Explained about Enums, Event Handlers,Proporties and few of WPF and Silverlight Concepts
http://blog.subhendu.info/index.php/proporties/
Reply | Email | Modify 
comment on article by Snehal On June 27, 2010
very useful article for beginners.....
Reply | Email | Modify 
hello by RIZVAN On September 19, 2010
hello
Reply | Email | Modify 
thanks by siddharth On November 11, 2010
the explanation is very lucid and is easy to understand for novice developers.
Reply | Email | Modify 
Property Article by Shahid On December 9, 2010
Very good article
Reply | Email | Modify 
Thanks by vasu On February 14, 2011
Thanks Rajesh, nice article.
Reply | Email | Modify 
A simple example for property can be find here by niranjan On June 22, 2011
Example program http://www.programcall.com/12/csnet/example-program-for-property-and-methods-of-a-class.aspx
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.