Codiqo

Learn C# · lesson 38 of 61 · about 8 minutes

Classes and Objects

Set up a sparring match: define your own types with classes, and create objects that each hold their own data.

What you'll learn

  • Write a class with fields and methods
  • Create objects with new
  • See that each object has its own data

A sparring match

After the battle, the hero spars with the arena's champion. Both are fighters: each has a name, some HP and the power of their hits, and each can hit the other. A Fighter class describes that once, and new Fighter() makes each one, with its own copy of the fields. you.Hit(champion) takes the hero's power off the champion's HP, never below 0, and a fighter who's down can't hit back.

A blueprint

A class is a blueprint; an object is one thing built from it.


class Penguin
{
public string Name = "";
public int Fish;
public void Eat() { Fish++; }
}

  • new Penguin() creates an object
  • p.Name reads a field; p.Eat() calls a method
  • Each object has its own copy of the fields
  • In a file with top-level statements, classes go after the main code

One object, one field

Lamp l = new Lamp();
l.On = true;
Console.WriteLine(l.On);

class Lamp
{
    public bool On;
}

Output

True

Using objects

Each new makes a separate object, so two penguins keep separate counts. A method like Eat() changes the fields of the object it's called on.

Two penguins

Penguin a = new Penguin();
a.Name = "Phoebe";
Penguin b = new Penguin();
b.Name = "Flipper";
a.Eat();
a.Eat();
b.Eat();
Console.WriteLine($"{a.Name} ate {a.Fish}, {b.Name} ate {b.Fish}");

class Penguin
{
    public string Name = "";
    public int Fish;
    public void Eat() { Fish++; }
}

Output

Phoebe ate 2, Flipper ate 1

Now try it yourself

This lesson is free in Codiqo, with 9 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.