Skip to content

Classes and Objects

The Course
•
30 min study

By now, a study task means a title, some minutes and a done flag. Keeping those in three separate variables, or three parallel lists, gets awkward quickly. A class defines a new type that bundles related data together with the methods that work on it. An object is one value of that type, created with new.

Think of StudyTask as the blueprint, and each new StudyTask(...) as a separate thing built from it.

A first class

A property holds a piece of the object's data, and is written with { get; set; }. The constructor is a special method with the same name as the class and no return type, which runs when the object is created. Its job is to set the object up. A method is declared inside the class and can use the object's properties directly.

public means code outside the class may use that member. There's one placement rule to learn too: in a file with top-level statements, class declarations must come after the statements. Otherwise you get error CS8803.

Each object has its own data C#
var first = new StudyTask("Read chapter", 25);
var second = new StudyTask("Practice", 40);

first.Done = true;

Console.WriteLine(first.Describe());
Console.WriteLine(second.Describe());
Console.WriteLine(second.Minutes);

class StudyTask
{
    public string Title { get; set; }
    public int Minutes { get; set; }
    public bool Done { get; set; }

    public StudyTask(string title, int minutes)
    {
        Title = title;
        Minutes = minutes;
    }

    public string Describe()
    {
        string state = Done ? "Done" : "Todo";
        return $"{state}: {Title} ({Minutes} min)";
    }
}
Check your prediction
Text
Done: Read chapter (25 min)
Todo: Practice (40 min)
40

Setting first.Done had no effect on second. Each object has its own values. Also note that Done wasn't set in the constructor, so it started at its default of false. Default values are 0 for numbers and false for bool.

The name StudyTask has a reason, by the way. .NET already has a type called Task for asynchronous work, so reusing that name in a real project invites confusion.

Methods with and without static

Look again at Describe: it has no static. On Day 3, static kept a top-level method from reading the main program's variables. Inside a class it means something related: a static method belongs to the type, not to any one object, so it has no Title or Minutes of its own to read. A method that uses an object's data, like Describe, must not be static, and you call it on an object: task.Describe(). A method that needs no particular object, like a rule about lengths, can be static, and you call it on the type name: StudyTask.IsValidLength(200).

On an object, or on the type C#
var task = new StudyTask("Read chapter", 25);
Console.WriteLine(task.Describe());
Console.WriteLine(StudyTask.IsValidLength(200));
Console.WriteLine(StudyTask.IsValidLength(40));

class StudyTask
{
    public string Title { get; set; }
    public int Minutes { get; set; }

    public StudyTask(string title, int minutes)
    {
        Title = title;
        Minutes = minutes;
    }

    public string Describe() => $"{Title} ({Minutes} min)";

    public static bool IsValidLength(int minutes) => minutes >= 1 && minutes <= 180;
}
Check your prediction
Text
Read chapter (25 min)
False
True

Try adding static to Describe. The compiler stops with error CS0120, "An object reference is required", at Title: a method that belongs to the type can't know which task's title you mean. So the Day 3 habit becomes a rule of thumb: in a class, use static only for methods that don't use the object's own data.

Objects in collections

A class is a type, so you can have a List<StudyTask> exactly as you had List<int>. Going through tasks and asking each for its data is the pattern behind most of the rest of this course.

A list of objects C#
var tasks = new List<StudyTask>
{
    new StudyTask("Read", 25),
    new StudyTask("Practice", 40),
    new StudyTask("Review", 10),
};
tasks[0].Done = true;

int remaining = 0;
foreach (StudyTask task in tasks)
{
    if (!task.Done)
    {
        remaining += task.Minutes;
    }
}
Console.WriteLine(remaining);

class StudyTask
{
    public string Title { get; set; }
    public int Minutes { get; set; }
    public bool Done { get; set; }

    public StudyTask(string title, int minutes)
    {
        Title = title;
        Minutes = minutes;
    }
}
Check your prediction
Text
50

Your turn

Exercise

A book class

Write a class Book with Title, Pages and PagesRead properties, where a constructor sets the title and page count. Add a method PagesLeft() that returns the pages remaining, and a method IsFinished() that returns a bool. Create a 200-page book, set PagesRead to 150, and print Pages left: 50 and Finished: False. Then set PagesRead to 200 and print Finished: True.

Your workspace C#
Console.WriteLine("Put your class under this line");
Hint 1: the idea

PagesLeft and IsFinished should be worked out from the two page properties each time, not stored separately.

Hint 2: a first step

Write the class with its properties and constructor, create one object, and print its Title.

Show one solution
C#
var book = new Book("C# Basics", 200);
book.PagesRead = 150;
Console.WriteLine($"Pages left: {book.PagesLeft()}");
Console.WriteLine($"Finished: {book.IsFinished()}");

book.PagesRead = 200;
Console.WriteLine($"Finished: {book.IsFinished()}");

class Book
{
    public string Title { get; set; }
    public int Pages { get; set; }
    public int PagesRead { get; set; }

    public Book(string title, int pages)
    {
        Title = title;
        Pages = pages;
    }

    public int PagesLeft()
    {
        return Pages - PagesRead;
    }

    public bool IsFinished()
    {
        return PagesRead >= Pages;
    }
}
Text
Pages left: 50
Finished: False
Finished: True

PagesLeft and IsFinished are methods that calculate from the stored values each time, so they're always up to date after PagesRead changes. IsFinished uses >=, not ==, so a reader who goes past the end still counts as finished. Neither method is static, because each needs one particular book's pages.

Nothing stops book.PagesRead = 500; or a book with -3 pages. Try them and see what the methods report. The next lesson fixes exactly this.

Was this article helpful?

Your response is saved on this device.