Lesson 8 of 10

Classes and properties

Goal

Constructors, private set and encapsulation

01

Explanation

A class is a template, and an object is an instance made from it with its own data, as in var hero = new Player("Layan", 100);. new calls the constructor, a method with the same name as the class and no return type, whose job is to set up the new object. Everything in a class is private unless you say otherwise, so anything you want to use from outside the class needs public in front of it.

A public field public int Hp; lets any code write hero.Hp = 9999. A property public int Hp { get; private set; }, however, can be read from anywhere but changed only from inside the class, so every change goes through the class's methods, and those methods enforce the rules of the game: damage never takes health below zero, and healing never goes over the maximum. This is called encapsulation.

You write a computed property with an arrow, as in public bool IsAlive => Hp > 0;. It isn't stored: it's calculated from Hp every time you read it, so it always agrees with it.

02

Your task

Turn the fields Name, MaxHp and Hp in Player into { get; private set; } properties, and make the constructor store the name and the maximum health and start the player at full health. Then make IsAlive true as long as Hp is above zero, make TakeDamage(amount) lower Hp without taking it below zero, and make Heal(amount) raise it without going over MaxHp, but never heal a player who has fallen.

Checks

6 checks
  1. The constructor stores the name and starts at full health
  2. TakeDamage lowers health
  3. Health never drops below zero, and IsAlive becomes false
  4. Heal raises health without going over MaxHp
  5. A player who has fallen can't be healed
  6. Name, MaxHp and Hp can be read from outside but not changed from there
03

Hints

0/3
Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.

Program.cs
OutputC# (Mono 6.6, Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

C# is the language behind Unity games and .NET apps. Every variable has a fixed type, programs are built from classes, and it comes with ready-made tools for most of what you need.

Beginner level, 10 lessons, 2.5 hours in total.