C#
Properties
Learn controlled access with property get/set accessors.
Properties
A property looks like a field from outside but works like a method inside. get is the read accessor, set is the write accessor. Properties expose a private field in a controlled way.
Example: public double Celsius { get { return celsius; } set { celsius = value; } }. Here value is a special variable that carries the assigned value. Inside set you can validate: for example, prevent a temperature from dropping below absolute zero.
get and set accessors
The get accessor returns a value; it answers a read request from outside. The set accessor receives the assigned value; you reach it with the value keyword and write it to the private field.
A property with only get is read-only: it cannot be changed from outside. A property with only set is write-only. Most of the time both are present. You can put any code inside accessors: validation, logging, side effects are all possible.
Exercise Add a property to the Temperature class
Define a Temperature class. Add a private double celsius; field. Then declare a public double Celsius property; in the get body write return celsius;, in the set body write celsius = value;. Inside Main create an instance, set Celsius = 36.5 and print Celsius.
Show example solution
Add a private celsius field and a Celsius property to Temperature. In Main write Temperature t = new Temperature(); t.Celsius = 36.5; Console.WriteLine(t.Celsius);
Example solution:
using System;
class Temperature
{
private double celsius;
public double Celsius
{
get { return celsius; }
set { celsius = value; }
}
}
class Program
{
static void Main()
{
Temperature t = new Temperature();
t.Celsius = 36.5;
Console.WriteLine(t.Celsius);
}
}
Test yourself
-
Complete the get accessor
public double Celsius { get { return ____; } }
Show answer
public double Celsius { get { return celsius; } }
-
Which is a read-only property?
- public string Name { get; }
- public string Name { get; set; }
- public string Name;
- public string Name { set; }
Show answer
public string Name { get; } — Correct. A property with only get is read-only.
-
Match each accessor to its behavior
- get
- Reading
- set
- Writing
- value
- Assigned value
- { get; }
- Read-only
Next lesson: Auto-properties