In C#, properties are named members of classes, structs, and interfaces. They provide a flexible mechanism to read, write, or compute the values of private fields through accessors.
Properties are an extension of fields and are accessed using the same syntax. Unlike fields, properties do not designate storage locations. Instead, properties have accessors that read, write, or compute their values.
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;
}
}
}