Codiqo

Learn C# · lesson 39 of 61 · about 9 minutes

Constructors and Properties

Pin quests on the board: set objects up with constructors, and expose data through properties.

What you'll learn

  • Write a constructor
  • Use auto-properties with get and set
  • Use object initialisers and ToString

The quest board

The guild hall has a quest board: clear the cave for 20 gold, and find the crown for 50. A quest should never exist without its title and reward, so Quest has a constructor that takes both and stores them in read-only properties. Done can be read by anyone but set only by the quest itself, through Complete(). The cave counts as cleared if the boss took at least 50 damage, and the crown quest if a crown dropped. ToString() decides how a quest prints, and the rewards of finished quests go into the gold.

Setting up objects

A constructor has the class's name and no return type. It runs when you call new: public Player(string name) { Name = name; }

A constructor

var p = new Pet("Phoebe");
Console.WriteLine(p.Name);

class Pet
{
    public string Name;

    public Pet(string name)
    {
        Name = name;
    }
}

Output

Phoebe

Properties

A property looks like a field but is read and written through get and set:

  • public string Name { get; set; }: read and write
  • public int Level { get; private set; } = 1;: only the class can change it
  • public bool IsPro => Level >= 10;: worked out each time

Override ToString() to control how an object prints.

A player

var ada = new Player("Ada");
ada.GainXp(250);
Console.WriteLine(ada);
var bo = new Player("Bo") { Country = "UK" };
Console.WriteLine($"{bo.Name} from {bo.Country}, level {bo.Level}");

class Player
{
    public string Name { get; }
    public string Country { get; set; } = "?";
    public int Xp { get; private set; }
    public int Level => 1 + Xp / 100;

    public Player(string name)
    {
        Name = name;
    }

    public void GainXp(int amount) => Xp += amount;
    public override string ToString() => $"{Name} (level {Level}, {Xp} XP)";
}

Output

Ada (level 3, 250 XP)
Bo from UK, level 1

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.