c# · level 2 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Click, click, reset, click. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Counter c = new Counter();
c.Click();
c.Click();
c.Reset();
c.Click();
Console.WriteLine(c);
class Counter
{
public int Clicks;
public void Click() { Clicks++; }
public void Reset() { Clicks = 0; }
public override string ToString() { return $"Clicks: {Clicks}"; }
}
your turn
Your turn. Make a song describe itself.
Pick a song and its artist on line 3. On line 17, make ToString return the title, the word by, the artist and the minutes in brackets, like Yellow by Coldplay (3 min).
output
press run to see what happens
fix it
The ticket prints its class name. Fix it!
output
press run to see what happens
- It prints
Ticket, the class name, so C# used theToStringevery object comes with. Why not yours? - To put your method in place of the one an object came with, you need one extra word.
- Change line 15 to start with
public override string ToString(), then press run.
nailed it
your objects can speak for themselves. :D
- A method inside a class works on its own object.
ToStringdecides how an object prints.overrideputs your version in place of the old one.
new words in your collection
- ToString
- override
This lesson isn’t saved. A free account remembers every lesson you finish.