Writing the Class in C#

Turn a class design into C# with private fields and public methods, then create objects with new and call their methods.

Apprentice · C# · OOP · Updated

By

After this lesson you can

  • Write a class with private fields and public methods
  • Create an object with new and call its methods

Key takeaways

  • Declare a class with class and a PascalCase name, and put its fields and methods between its curly braces.
  • Mark fields private so only the class's own code can use them. That's encapsulation, and outside code that tries doesn't compile.
  • Methods that use an object's fields aren't static: each one works on the object it's called on, such as kitchenFridge.AddItem(400).
  • new Refrigerator() creates an object. Each object has its own fields, so changing one doesn't touch another.

Now turn the Refrigerator design into C#.

Declaring the class

A class is declared with the word class and its name, in PascalCase. Everything the class knows and does goes between its curly braces:

public class Refrigerator
{
    // the class's fields and methods go here
}

In a project, each class usually lives in its own file, named after it: Refrigerator.cs. In a single-file program, write your top-level code first and your classes at the bottom of the file.

Fields: what it knows

A variable that belongs to an object is a field. Declare fields inside the class, outside any method. Mark them private, so only the object's own methods can use them:

public class Refrigerator
{
    private int temperature = 37;
    private int capacity = 1500;
    private int usedSpace = 0;
}

public and private are access modifiers. They decide who may use a member:

Modifier Who can use it
public any code, anywhere
private only code inside this class

Keeping fields private is called encapsulation: the object's data is sealed inside it, and the outside world works with it only through the methods the class chooses to offer. Nobody can set usedSpace to -400 by accident.

Methods: what it does

Methods inside a class can read and change its fields. They aren't static: each method works on one particular object, the one it was called on.

public class Refrigerator
{
    private int temperature = 37;
    private int capacity = 1500;
    private int usedSpace = 0;

    // Adds an item if there's room: returns true if it fit, false if not.
    public bool AddItem(int itemSize)
    {
        if (usedSpace + itemSize <= capacity)
        {
            usedSpace += itemSize;
            return true;
        }
        return false;
    }

    public int GetFreeSpace()
    {
        return capacity - usedSpace;
    }

    public int GetTemperature()
    {
        return temperature;
    }
}

Creating an object

A class is a new type, so you can declare a variable of that type. To create an object, an instance of the class, use new and the class's name followed by parentheses:

Refrigerator kitchenFridge = new Refrigerator();

bool fitted = kitchenFridge.AddItem(400);
Console.WriteLine(quot;Milk fitted: {fitted}");
Console.WriteLine(quot;Free space: {kitchenFridge.GetFreeSpace()}");
Console.WriteLine(quot;Temperature: {kitchenFridge.GetTemperature()}");

public class Refrigerator
{
    private int temperature = 37;
    private int capacity = 1500;
    private int usedSpace = 0;

    public bool AddItem(int itemSize)
    {
        if (usedSpace + itemSize <= capacity)
        {
            usedSpace += itemSize;
            return true;
        }
        return false;
    }

    public int GetFreeSpace()
    {
        return capacity - usedSpace;
    }

    public int GetTemperature()
    {
        return temperature;
    }
}
Milk fitted: True
Free space: 1100
Temperature: 37

You call an object's method with a period: kitchenFridge.AddItem(400), just as you call name.ToUpper() on a string.

Each object has its own state

Two objects made from the same class are separate. Changing one doesn't touch the other:

Refrigerator kitchenFridge = new Refrigerator();
Refrigerator garageFridge = new Refrigerator();

kitchenFridge.AddItem(1000);

Console.WriteLine(quot;Kitchen: {kitchenFridge.GetFreeSpace()} free");
Console.WriteLine(quot;Garage: {garageFridge.GetFreeSpace()} free");

public class Refrigerator
{
    private int capacity = 1500;
    private int usedSpace = 0;

    public bool AddItem(int itemSize)
    {
        if (usedSpace + itemSize <= capacity)
        {
            usedSpace += itemSize;
            return true;
        }
        return false;
    }

    public int GetFreeSpace()
    {
        return capacity - usedSpace;
    }
}
Kitchen: 500 free
Garage: 1500 free

Private really means private

Code outside the class can't touch a private field. This doesn't compile:

Refrigerator kitchenFridge = new Refrigerator();
kitchenFridge.usedSpace = -400;

public class Refrigerator
{
    private int usedSpace = 0;
}

The compiler stops it with 'Refrigerator.usedSpace' is inaccessible due to its protection level. That's encapsulation doing its job.

Do it: write a kitchen cupboard class

The kitchen needs a cupboard as well as a refrigerator. A cupboard holds plates, up to 12 of them, and it starts empty. Like the refrigerator, it guards its own count: plates go in and out only through its methods, and it refuses what it can't do.

The class keeps two numbers, as private fields:

  • how many plates it can hold: 12;
  • how many plates it holds now: 0 when it's new.

AddPlates and TakePlates each get one value:

  • count: how many plates to add or take away, an int (8).

For example:

Cupboard cupboard = new Cupboard();
cupboard.AddPlates(8);
cupboard.AddPlates(5);
cupboard.TakePlates(3);
Call Returns Why Plates after it
AddPlates(8) true 0 + 8 = 8, and 8 is 12 or fewer 8
AddPlates(5) false 8 + 5 = 13, more than 12, so nothing changes 8
TakePlates(3) true it holds 8, so 3 can come out 5

So after these three calls, cupboard.GetPlates() returns 5.

Your job: finish the class Cupboard.

  • Add two private int fields: how many plates it can hold (12), and how many it holds now (0).
  • AddPlates(int count): if the plates it holds now plus count make 12 or fewer, add them and return true. Otherwise return false and change nothing.
  • TakePlates(int count): if it holds at least count plates, take them away and return true. Otherwise return false and change nothing.
  • GetPlates(): return how many plates it holds now.
  • Each cupboard keeps its own count: plates added to one don't appear in another.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

A class bundles state and behavior into one type: private fields hold what it knows, public methods offer what it does, and new makes as many independent objects from it as you need.

Key terms

Cheat sheets