Properties represent a type’s data or state. They expose this data by providing read/write access to a type’s fields. Properties and methods inform the user of a type’s behavior and how it's used.
In C#, they are special methods in a class but accessed like fields.
// Field
private string _name = "John Doe";
// Property
public string Name
{
get => _name;
set => _name = value;
}
// Methods
// Getter converted to method by CIL
.method public hidebysig specialname
instance bool get_Name () cil managed
// Setter converted to method by CIL
.method public hidebysig specialname
instance void set_Name (
bool 'value'
) cil managed
// Auto Property (auto-generated backing field)
public bool Name { get; set; }
// Property encapsulating a private field
public bool Name
{
get { return _name; }
set { _name = value; }
}
// Expression-body Property (encapsulating a private field)
public bool Name
{
get => _name;
set => _name = value;
}
The user can read a property to retrieve information from a type or write to change the state of a type. The access modifier determines the level of exposure.
// Read-only access.
public string Name => _name;
public string Name
{
get => _name;
}
// Write only access.
public string Name
{
set => _name = value;
}
// Read and write access.
public bool Name
{
get => _name;
set => _name = value;
}
// Read-only access within the type.
public string Name
{
private get => _name;
set => _name = value;
}
// Write only access within the type.
public string Name
{
get => _name;
private set => _name = value;
}
<aside> <img src="/icons/report_red.svg" alt="/icons/report_red.svg" width="40px" /> Pro-Tip
<aside>
<img src="/icons/light-bulb_lightgray.svg" alt="/icons/light-bulb_lightgray.svg" width="40px" /> The get or “getter” method should only return a value.
</aside>
<aside>
<img src="/icons/light-bulb_lightgray.svg" alt="/icons/light-bulb_lightgray.svg" width="40px" /> The set or “setter” method can have calculations to produce a final value.
</aside>
</aside>