Properties in C#……………

This article is designed to further your knowledge about properties in the C# language. Read how Rajesh uses get and set methods to access these properties.

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.

The complete program is shown below. :

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
}
}

SHARE THE KNOWLEDGE


  

 

Advertisements

About Dinesh

I am engineering student........ I am selected in Microsoft Student Partner as MSP............

Posted on August 10, 2011, in .NET, Knowledge. Bookmark the permalink. Leave a comment.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: