C#
Putting it together
Combine all layers into a working app.
Tying it together with a console menu
The final lesson combines all pieces inside Main: add a book, print the count, save to a file. This is the working whole of the project.
A menu loop is also possible: read commands with while, dispatch with switch. This lesson starts with a simple flow: add, list and save back to back.
Flow design
A good Main flow: first prepare data (add books), then query (FindByAuthor or Count), finally save (Save). Each step calls a member gained in a previous lesson.
This shape shows the cumulative nature of the project: each lesson laid one brick, the final lesson turns bricks into a building. Later you can add a menu loop and error handling.
Exercise Combine the whole flow
The Library class below has all its methods ready. In Main: add two books (lib.Add), print the count (lib.Count), save to file (lib.Save). Print the count with Console.WriteLine.
Show example solution
lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" }); lib.Add(new Book { Title = "Karamazov Brothers", Author = "Dostoevsky" }); Console.WriteLine(lib.Count); lib.Save("books.txt");
Example solution:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
class Book
{
public string Title { get; set; }
public string Author { get; set; }
}
class Library
{
private List<Book> _books = new List<Book>();
public void Add(Book b) => _books.Add(b);
public int Count => _books.Count;
public IEnumerable<Book> FindByAuthor(string author)
{
return _books.Where(b => b.Author == author);
}
public void Save(string path)
{
string text = JsonSerializer.Serialize(_books);
File.WriteAllText(path, text);
}
}
class Program
{
static void Main()
{
var lib = new Library();
lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" });
lib.Add(new Book { Title = "Karamazov Brothers", Author = "Dostoevsky" });
Console.WriteLine(lib.Count);
lib.Save("books.txt");
}
}
Test yourself
-
Match the step to its function
- Add
- Add a book
- Count
- Print the count
- FindByAuthor
- Search by author
- Save
- Save to file
-
What ties the project together?
- The Main method
- The Book class
- The using line
- The comments
Show answer
The Main method — Correct. The Main method calls all pieces and ties them together.
-
Complete the Save call
lib.____("books.txt");
Show answer
lib.Save("books.txt");
Next lesson: Intermediate section exam