×

c# · level 2 · unit 2 · lesson 1

  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

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#.