c# · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a blueprint, and objects are built from it.
So far every value has had a ready-made type, like string or int. A class lets you design your own. It is a blueprint: it says what every pet has, such as a name and an age, but it is not a pet itself.
new Pet() builds an from the blueprint. Each object has its own fields, the named boxes the class lists. rex.Name reaches into Rex's box, and changing it leaves Tibbles alone. The word lets code outside the class use a .
Your classes go at the bottom of the file, below the main lines. For now, printing a whole object shows only its class name, Pet.
using System;
Pet rex = new Pet();
rex.Name = "Rex";
rex.Age = 3;
Pet tibbles = new Pet();
tibbles.Name = "Tibbles";
tibbles.Age = 7;
Console.WriteLine($"{rex.Name} is {rex.Age}");
Console.WriteLine($"{tibbles.Name} is {tibbles.Age}");
Console.WriteLine(rex);
class Pet
{
public string Name;
public int Age;
} Class names and public fields start with a capital letter in C#.
guess first
Two cars, one paint job. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
using System;
Car a = new Car();
a.Colour = "red";
Car b = new Car();
b.Colour = "blue";
a.Colour = "green";
Console.WriteLine($"{a.Colour} {b.Colour}");
class Car
{
public string Colour;
}
your turn
Your turn. Build your favourite book.
On line 11, name the second field so it matches fav.Author. Then put your favourite book and its author on lines 4 and 5, and press run.
output
press run to see what happens
fix it
The robot will not say its name. Fix it!
output
press run to see what happens
- C# says
CS0122on line 4:Nameis inaccessible. Who is allowed to use the field? - Without a word in front, a field can only be used by code inside its own class.
- Change line 9 to
public string Name;, then press run.
nailed it
you designed your own type. :D
- A class is a blueprint, and
newbuilds an object. - Every object has its own fields.
publiclets outside code use a field.
new words in your collection
- class
- object
- field
- public
This lesson isn’t saved. A free account remembers every lesson you finish.