Properties in C#

Abhisek
Posted by Abhisek under C# category on | Views : 1765
PROPERTY:-


Property acts as a cross link between the field and the method. Actually it behaves as a field. We can retrieve and store data from the field using property.

The compiler automatically translates the field like property into a call like special method called as 'accessor" . In property there are two accessor and that are used to save value and retrieve value from the field. The two properties are 'get' and 'set'.

The get property is used to retrieve a value from the field and the set property is used to assign a value to a field .

Depending on there use properties are categorised into three types,

ReadWrite Property:- When both get and set properties are present it is called as ReadWrite Property.

ReadOnly Property:- When there is only get accessor it is called as ReadOnly Property.

WriteOnly Property:- When there is only set accessor, it is called as WriteOnly Property.

See the following program which demonstrates how the properties are used,


class GetSet
{
int len;
public int Len
{
get
{
return this.len;
}
set
{
this.len = value;
}
}
}
class MainClass
{
static void Main(string args[])
{
GetSet gs=new GetSet();
gs.Len=25;
int r = gs.Len;
Console.WriteLine("Length={0}",r);
}
}



The output of the above program will be Length=25.

We are passing the value to the field set property

this.len = value;
gs.Len=25;

and accessing the value using the get property

return this.len;
int r = gs.Len;

Comments or Responses

Login to post response