Skip to content
Tutorials Center
My learning

Topics

Lesson 176 of 182 ยท Projects

Project: Library Management System

Build a library system in C# in three stages: books and members as classes with rules, borrowing and returning with fines, LINQ reports, and a console menu that runs a script of commands.

A library is a friendly problem for practicing everyday C#. There are things (books, members), rules (a member may borrow only three books, a book can only be on loan to one person, late returns cost money) and questions to ask the data (who has overdue books? which authors are most popular?). You will model the things with classes and records, enforce the rules in one place, answer the questions with LINQ, and finish with a console menu.

You build it in three stages, and every stage is a complete program you can run and modify:

Stage What you build Tools
1 Books, members, borrowing and returning classes, records, dictionaries, exceptions
2 Overdue lists, fines and reports LINQ operators, DateOnly, string formatting
3 A console menu that processes commands switch expressions, input, parsing

To keep the programs repeatable, "today" is a field you can set, not DateOnly.FromDateTime(DateTime.Today). Tests and demos that depend on the real clock give different answers every day, which makes bugs hard to reproduce.

Design first

Before writing code, decide where each rule lives.

  • A Book is data: an ISBN, a title, an author and a number of copies owned. It does not know who has borrowed it.
  • A Member has an ID and a name.
  • A Loan records one borrowing: which book, which member, when it was borrowed and when it is due. Making it an immutable record means a loan never changes. Returning a book removes the loan and creates a history entry instead.
  • The Library class owns the collections and is the only place that enforces rules. Because every change goes through Library, no other code can put the system into an invalid state.

The rules we will enforce: a loan lasts 14 days, a member may hold at most 3 books, nobody may borrow a title with no copies left, and a late return costs 0.25 per day (in the currency of your choice, stored as decimal).

Stage 1: books, members and loans

C# Stage 1: the model and the borrowing rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that the order of checks matters. Ada's second attempt at Dune reports "already has" rather than "no copy available" because the personal check comes first, which gives the most useful message. Also notice that Borrow either throws before changing anything or adds the loan as its last step. That is how you keep a system consistent: validate everything, then change state.

class Library(DateOnly today) is a primary constructor. The same syntax makes LibraryException(string message) : Exception(message) a one-line exception class.

Stage 2: returns, fines and reports

Now add Return, which removes the loan, computes the fine and records history. Then ask the data some questions with LINQ. To keep the lesson short, the program below repeats the model from stage 1 in a compact form with Return and Fine added; in your own project you would extend the same Library class.

C# Stage 2: returning books, fines and LINQ reports

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A few design points are worth noticing:

  • Money is decimal and the fine is a pure function (FineFor) of the loan and the return date. A pure function is trivial to test.
  • DayNumber converts a DateOnly into an integer, so subtracting two dates gives whole days with no time-zone trouble.
  • Fines are only collected on return. The overdue report shows what would be charged, and Overdue is a LINQ query expression with let to avoid computing the days twice.
  • The history list separates "what is out now" from "what happened". The author report reads both lists and uses Join to connect an ISBN to its book.

Stage 3: a console menu

Real library staff would use a menu: type a command, see a result, repeat. The program below reads its commands from an array so that it runs unattended in the editor; to make it interactive, replace the array with Console.ReadLine() in a loop (see input). The loop is the classic read, parse, dispatch pattern: split a command line into words, pick the action with a switch on the first word, and catch the rule violations from the library.

C# Stage 3: a command loop for the library

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The switch uses list patterns (["borrow", var who, var isbn]) to match command shapes, a feature covered in list patterns. Patterns are checked in order, so the specific borrow shape comes before the general "borrow with wrong arguments" case.

Ideas to extend it

  1. Reservations: a queue of members waiting for each book; return a book and offer it to the first in line.
  2. Persistence: save the catalog and loans as JSON with System.Text.Json and load them at startup.
  3. Search: a Search(string text) that matches titles and authors case-insensitively and ranks title matches first.
  4. Different member types: students with longer loans, children with a limit of two, using inheritance or composition.
  5. Tests: write unit tests for FineFor and each refusal rule. The pure fine function is the easiest place to start.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the Library class own all the collections and enforce every rule?

    When every change goes through one class, rules such as the loan limit cannot be bypassed.
  2. 2. Why is money stored as decimal in this project?

    Binary floating point cannot represent many decimal fractions exactly. decimal is designed for money.
  3. 3. What does the validate-then-change approach in Borrow guarantee?

    All checks run before the loan is added, so when an exception is thrown nothing has been modified.
  4. 4. What does the pattern ["borrow", var who, var isbn] match?

    A list pattern without .. matches exactly its number of items; var captures the second and third elements.

Summary

  • Model the data with records, put the rules in one owner class and throw a specific exception when a rule is broken.
  • Validate first, then change state, so a refusal never leaves half-done work.
  • Use decimal for money and keep calculations such as fines in small pure functions.
  • LINQ turns the lists of loans into reports: filtering, grouping, joining and ordering in a few lines.
  • A console menu is a read-parse-dispatch loop; list patterns make command parsing readable.

Next: build a parser in Project: Console Calculator, or review the Bank Account project for atomic operations.