×

c# · level 2 · unit 2 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Objects can do things, and describe themselves.

A class can hold methods as well as fields. A method written inside the class works on its own object, so rex.Birthday() adds one to Rex's age and nobody else's. Inside the class, Age means this object's Age.

Every object comes with a method, which C# calls to turn it into text whenever you print it or put it in $"...". The one it comes with only gives the class name. Write and yours is used instead: override means replacing the method an object came with.

using System;

Pet rex = new Pet("Rex", 3);
rex.Birthday();
Console.WriteLine(rex);
Console.WriteLine($"Happy birthday, {rex}!");

class Pet
{
    public string Name;
    public int Age;
    public Pet(string name, int age)
    {
        Name = name;
        Age = age;
    }
    public void Birthday() { Age++; }
    public override string ToString() { return $"{Name} ({Age})"; }
}

Short methods fit on one line, like your one-line functions.