Skip to content

Checkpoint: Several Source Files

The Course
•
30 min study

Real programs don't live in a single file. In C#, every .cs file in a project is compiled together, so a class in one file is available to all the others. By convention, each class gets its own file, named after it.

There are three rules to know:

  • Only one file may have top-level statements. That file is where the program starts, usually Program.cs. All other files only declare types.
  • A namespace groups related names. namespace Study; at the top of a file puts its types in Study. It's how a large program avoids clashes, such as two different types named Task.
  • using brings a namespace in. Other files write using Study; to use its names without a prefix.

Two files, one program

Click the file tabs below to read both files, then predict the output. Session is a record that also has a method: records can have a body, just as classes do. public makes it usable by other code. Types without an access keyword are internal, which means usable anywhere in the same project.

Program.cs and Session.cs C#
using Study; var sessions = new List<Session> { new Session("Read", 25), new Session("Practice", 40), }; int total = 0; foreach (Session session in sessions) { Console.WriteLine(session.Describe()); total += session.Minutes; } Console.WriteLine($"Total: {total} minutes"); namespace Study; public record Session(string Title, int Minutes) { public string Describe() { return $"{Title}: {Minutes} minutes"; } }
Check your prediction
Text
Read: 25 minutes
Practice: 40 minutes
Total: 65 minutes

Delete the using Study; line in Program.cs, and read what the compiler reports about Session. Then restore it.

A single-file version, for comparison C#
var session = new Session("Read", 25);
Console.WriteLine(session.Describe());

record Session(string Title, int Minutes)
{
    public string Describe()
    {
        return $"{Title}: {Minutes} minutes";
    }
}
Check your prediction
Text
Read: 25 minutes

The compiler treats these two versions in the same way. Splitting files is for the people reading the code. When two files both have top-level statements, though, the compiler can't tell where to start.

Two starting points are one too many C#
Console.WriteLine("One"); Console.WriteLine("Two");
Check your prediction
Text
error CS8802: Only one compilation unit can have top-level statements.

You'll need this in a moment: your application and your checks each want their own starting point. So they become two separate sets of files that share the same class, and one of them is run at a time.

A computed property that needs a loop

On Day 5, computed properties were one expression after =>, such as public int PagesLeft => Pages - PagesRead;. A total over a list needs a loop, and a loop doesn't fit in one expression. For that, write the property's get as a block: the code between the braces runs each time the property is read, and return gives its value. It's still read-only, because there's no set.

A get block with a loop C#
var shelf = new Shelf();
shelf.Add(120);
shelf.Add(300);
Console.WriteLine(shelf.Count);
Console.WriteLine(shelf.TotalPages);

class Shelf
{
    private readonly List<int> pages = new();

    public int Count => pages.Count;

    public int TotalPages
    {
        get
        {
            int total = 0;
            foreach (int count in pages)
            {
                total += count;
            }
            return total;
        }
    }

    public void Add(int count)
    {
        pages.Add(count);
    }
}
Check your prediction
Text
2
420

Count fits in one expression, so it uses =>. TotalPages needs several statements, so it uses a get block. Both are worked out from the list each time, so neither can disagree with it. You'll need the second form in the exercise below.

Build it yourself

This pulls together today's lessons, with some files of your own to organize.

Exercise

A session log in two files

The workspace below has the two files from above, and a third tab, SessionLog.cs, with a class to finish. SessionLog has a private list of Session, a method TryAdd(string line) that parses lines of the form 25 Read chapter and returns false for bad text or minutes outside 1 to 180, and a read-only TotalMinutes computed property, written with a get block like TotalPages above. Change Program.cs to read all of standard input, add each line, and print Total: 65 minutes and Rejected: 1 for the input 25 Read, nope and 40 Practice.

Use #nullable enable at the top of any file that writes string?.

Your workspace C#
using Study; var sessions = new List<Session> { new Session("Read", 25), new Session("Practice", 40), }; int total = 0; foreach (Session session in sessions) { Console.WriteLine(session.Describe()); total += session.Minutes; } Console.WriteLine($"Total: {total} minutes"); namespace Study; public record Session(string Title, int Minutes) { public string Describe() { return $"{Title}: {Minutes} minutes"; } } namespace Study; public class SessionLog { // Replace this with the real rules from the brief. public bool TryAdd(string line) { return true; } } 25 Read nope 40 Practice
Hint 1: the idea

Program.cs should only move lines from the input to the log and print the results. All parsing and rules belong in SessionLog.

Hint 2: a first step

The supplied TryAdd always returns true. Call it once from Program.cs to prove the two files are connected before you write any rules.

Show one solution

This listing marks each file with a // File: comment. Each section goes in its own tab or file. The comment is only a label: it does not create a file.

C#
// File: Program.cs
#nullable enable

using Study;

var log = new SessionLog();
int rejected = 0;

string? line;
while ((line = Console.ReadLine()) is not null)
{
    if (!log.TryAdd(line))
    {
        rejected++;
    }
}

Console.WriteLine($"Total: {log.TotalMinutes} minutes");
Console.WriteLine($"Rejected: {rejected}");
// File: Session.cs
namespace Study;

public record Session(string Title, int Minutes)
{
    public string Describe()
    {
        return $"{Title}: {Minutes} minutes";
    }
}
// File: SessionLog.cs
namespace Study;

public class SessionLog
{
    private readonly List<Session> sessions = new();

    public int TotalMinutes
    {
        get
        {
            int total = 0;
            foreach (Session session in sessions)
            {
                total += session.Minutes;
            }
            return total;
        }
    }

    public bool TryAdd(string line)
    {
        string[] parts = line.Split(' ', 2);
        if (parts.Length != 2 || !int.TryParse(parts[0], out int minutes))
        {
            return false;
        }
        if (minutes < 1 || minutes > 180)
        {
            return false;
        }
        sessions.Add(new Session(parts[1], minutes));
        return true;
    }
}
Text
Total: 65 minutes
Rejected: 1

Each file has one job. Program.cs reads input and prints, Session.cs describes one session, and SessionLog.cs owns the rules, so the 1-to-180 check is written once, in the class that stores the sessions. TotalMinutes is worked out from the list each time it's read, rather than kept in a separate counter, so it can never disagree with the sessions. (If you did the optional LINQ section on Day 4, sessions.Sum(session => session.Minutes) does the same loop in one line: the lambda says which number to add up for each session.)

Tomorrow you'll build the planner in this same layout. Before moving on, explain to yourself why Program.cs contains no validation rules at all, and what you'd have to change to read tasks from somewhere other than standard input.

Was this article helpful?

Your response is saved on this device.