← C# from Scratch
Lesson 31 of 39 · 10 XP
Properties
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
A property looks like a field from outside, but inside it's a pair of methods, get and set:
class Player
{
private int hp;
public int Hp
{
get { return hp; }
set { hp = Math.Clamp(value, 0, MaxHp); } // value is what's being assigned
}
public int MaxHp { get; } = 100; // read-only
public string Name { get; set; } // an auto-property: the compiler creates the field itself
public bool IsDead => Hp == 0; // computed
}
p.Hp = 500; // calls set → becomes 100
p.Hp -= 130; // get, then set → 0
private set— everyone can read it, only the class itself can change it;init— can only be set at creation:new Player { Name = "Kai" }.
Properties are the C# standard: a class's public data is made into properties, not public fields.
Task. Finish Temperature: a Celsius property (get/set) and a computed Fahrenheit (C × 9 / 5 + 32)
with a set that converts back to Celsius. Celsius never goes below -273.15 °C.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.