TExcelTAD
Home › C# › C# Mini Project

C# Mini Project: Library Manager

In this project you will build a small library management console application step by step. It brings together much of what this course covered: records and classes, encapsulation, enums, collections, exceptions, LINQ and events. Each step is a complete, runnable program that extends the previous one, so you can experiment at every stage.

What the finished app can do:

  • keep a catalogue of books and a list of members,
  • lend books to members and take them back, enforcing rules (a book can only be lent once, members have a borrowing limit),
  • report on availability, overdue loans and fines,
  • notify listeners when something happens.

Note: A real app would read commands with Console.ReadLine() and store data in files or a database. To keep every step deterministic, we drive the library with a fixed "script" of actions and use day numbers instead of real dates.

Step 1: Modelling books

Start with the data. A book's identity (ISBN, title, author, year) never changes, so a record is a good fit. Whether it is currently on loan is tracked separately by the library.

csharp · try it yourself
using System;
using System.Collections.Generic;

var books = new List<Book>
{
    new("978-0441013593", "Dune", "Frank Herbert", 1965),
    new("978-0547928227", "The Hobbit", "J. R. R. Tolkien", 1937),
    new("978-0451524935", "1984", "George Orwell", 1949),
};

foreach (var book in books)
    Console.WriteLine(book);

Console.WriteLine(books[0] == new Book("978-0441013593", "Dune", "Frank Herbert", 1965));

record Book(string Isbn, string Title, string Author, int Year)
{
    public override string ToString() => 
quot;{Title} by {Author} ({Year})"; }
Dune by Frank Herbert (1965)
The Hobbit by J. R. R. Tolkien (1937)
1984 by George Orwell (1949)
True

We overrode ToString to get a friendlier format than the default record output, and value equality means two Book objects with the same data are equal.

Step 2: A Library class with encapsulated state

Next, a Library class owns the catalogue. Its collections are private; the outside world can only add and search books through methods. A dictionary keyed by ISBN gives fast lookups, and LINQ handles searching.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var library = new Library();
library.AddBook(new("978-0441013593", "Dune", "Frank Herbert", 1965));
library.AddBook(new("978-0547928227", "The Hobbit", "J. R. R. Tolkien", 1937));
library.AddBook(new("978-0451524935", "1984", "George Orwell", 1949));
library.AddBook(new("978-0261103573", "The Fellowship of the Ring", "J. R. R. Tolkien", 1954));

Console.WriteLine(
quot;Books in catalogue: {library.Count}"); Console.WriteLine("Search 'tolkien':"); foreach (var b in library.Search("tolkien")) Console.WriteLine(
quot; {b}"); try { library.AddBook(new("978-0441013593", "Dune (copy)", "Frank Herbert", 1965)); } catch (InvalidOperationException ex) { Console.WriteLine(
quot;Error: {ex.Message}"); } record Book(string Isbn, string Title, string Author, int Year) { public override string ToString() =>
quot;{Title} by {Author} ({Year})"; } class Library { private readonly Dictionary<string, Book> _books = new(); public int Count => _books.Count; public void AddBook(Book book) { if (!_books.TryAdd(book.Isbn, book)) throw new InvalidOperationException(
quot;A book with ISBN {book.Isbn} already exists."); } public IEnumerable<Book> Search(string text) => _books.Values .Where(b => b.Title.Contains(text, StringComparison.OrdinalIgnoreCase) || b.Author.Contains(text, StringComparison.OrdinalIgnoreCase)) .OrderBy(b => b.Year); }
Books in catalogue: 4
Search 'tolkien':
  The Hobbit by J. R. R. Tolkien (1937)
  The Fellowship of the Ring by J. R. R. Tolkien (1954)
Error: A book with ISBN 978-0441013593 already exists.

Step 3: Members, loans and business rules

Now the core feature: lending. A Loan record connects a book, a member and the day it was borrowed. The library enforces the rules and reports problems with exceptions; the caller decides how to show them.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var lib = new Library();
lib.AddBook(new("111", "Dune", "Frank Herbert", 1965));
lib.AddBook(new("222", "The Hobbit", "J. R. R. Tolkien", 1937));
lib.AddBook(new("333", "1984", "George Orwell", 1949));
lib.AddMember(new Member(1, "Alice", MembershipType.Standard));
lib.AddMember(new Member(2, "Bob", MembershipType.Student));

void Try(string description, Action action)
{
    try { action(); Console.WriteLine(
quot;OK {description}"); } catch (Exception ex) when (ex is InvalidOperationException or KeyNotFoundException) { Console.WriteLine(
quot;FAIL {description}: {ex.Message}"); } } Try("Alice borrows Dune", () => lib.Lend("111", 1, day: 1)); Try("Bob borrows Dune", () => lib.Lend("111", 2, day: 2)); Try("Bob borrows The Hobbit", () => lib.Lend("222", 2, day: 2)); Try("Bob borrows 1984", () => lib.Lend("333", 2, day: 3)); Try("Alice returns Dune", () => lib.Return("111", day: 10)); Try("Bob borrows Dune", () => lib.Lend("111", 2, day: 11)); Try("Carol borrows 1984", () => lib.Lend("333", 3, day: 12)); Console.WriteLine(
quot;Available: {string.Join(", ", lib.Available().Select(b => b.Title))}"); enum MembershipType { Student, Standard } record Book(string Isbn, string Title, string Author, int Year); record Member(int Id, string Name, MembershipType Type) { public int MaxLoans => Type == MembershipType.Student ? 1 : 3; } record Loan(Book Book, Member Member, int Day); class Library { private readonly Dictionary<string, Book> _books = new(); private readonly Dictionary<int, Member> _members = new(); private readonly Dictionary<string, Loan> _loans = new(); // ISBN -> active loan public void AddBook(Book book) => _books.Add(book.Isbn, book); public void AddMember(Member member) => _members.Add(member.Id, member); public void Lend(string isbn, int memberId, int day) { if (!_books.TryGetValue(isbn, out Book book)) throw new KeyNotFoundException(
quot;Unknown book {isbn}."); if (!_members.TryGetValue(memberId, out Member member)) throw new KeyNotFoundException(
quot;Unknown member {memberId}."); if (_loans.ContainsKey(isbn)) throw new InvalidOperationException(
quot;'{book.Title}' is already on loan."); int current = _loans.Values.Count(l => l.Member.Id == memberId); if (current >= member.MaxLoans) throw new InvalidOperationException(
quot;{member.Name} reached the limit of {member.MaxLoans} loan(s)."); _loans[isbn] = new Loan(book, member, day); } public void Return(string isbn, int day) { if (!_loans.Remove(isbn)) throw new InvalidOperationException(
quot;Book {isbn} is not on loan."); } public IEnumerable<Book> Available() => _books.Values.Where(b => !_loans.ContainsKey(b.Isbn)); }
OK    Alice borrows Dune
FAIL  Bob borrows Dune: 'Dune' is already on loan.
OK    Bob borrows The Hobbit
FAIL  Bob borrows 1984: Bob reached the limit of 1 loan(s).
OK    Alice returns Dune
FAIL  Bob borrows Dune: Bob reached the limit of 1 loan(s).
FAIL  Carol borrows 1984: Unknown member 3.
Available: Dune, 1984

Notice the exception filter when (ex is … or …): only the expected business errors are reported; a genuine bug elsewhere would still surface. The local function Try keeps the script tidy.

Step 4: Due dates, fines and events

Finally, let's add time. Loans are due after 14 days; late returns cost 0.25 per day. The library raises events whenever a book is lent or returned, and a separate ActivityLog subscribes to them — the library does not need to know who is listening. A report at the end uses LINQ grouping.

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var lib = new Library();
var log = new ActivityLog();
lib.BookLent += log.OnLent;
lib.BookReturned += log.OnReturned;

lib.AddBook(new("111", "Dune", "Frank Herbert"));
lib.AddBook(new("222", "The Hobbit", "J. R. R. Tolkien"));
lib.AddBook(new("333", "1984", "George Orwell"));
lib.AddBook(new("444", "Emma", "Jane Austen"));
var alice = lib.AddMember("Alice");
var bob = lib.AddMember("Bob");

lib.Lend("111", alice, day: 1);
lib.Lend("222", bob, day: 3);
lib.Lend("333", alice, day: 5);
lib.Return("111", day: 12);     // on time
lib.Return("222", day: 24);     // 7 days late

Console.WriteLine();
Console.WriteLine("== Report on day 30 ==");
foreach (var loan in lib.Overdue(today: 30))
    Console.WriteLine(
quot;OVERDUE {loan.Book.Title} ({loan.Member.Name}), due day {loan.DueDay}"); foreach (var (name, total) in lib.FinesByMember()) Console.WriteLine(
quot;Fines {name}: {total:F2}"); Console.WriteLine(
quot;On shelf {string.Join(", ", lib.Available().Select(b => b.Title))}"); record Book(string Isbn, string Title, string Author); record Member(int Id, string Name); record Loan(Book Book, Member Member, int Day) { public const int LoanDays = 14; public int DueDay => Day + LoanDays; } class Library { public const decimal FinePerDay = 0.25m; private readonly Dictionary<string, Book> _books = new(); private readonly List<Member> _members = new(); private readonly Dictionary<string, Loan> _active = new(); private readonly List<(Member Member, decimal Amount)> _fines = new(); public event Action<Loan> BookLent; public event Action<Loan, int, decimal> BookReturned; public void AddBook(Book book) => _books.Add(book.Isbn, book); public Member AddMember(string name) { var member = new Member(_members.Count + 1, name); _members.Add(member); return member; } public void Lend(string isbn, Member member, int day) { if (_active.ContainsKey(isbn)) throw new InvalidOperationException("Already on loan."); var loan = new Loan(_books[isbn], member, day); _active[isbn] = loan; BookLent?.Invoke(loan); } public void Return(string isbn, int day) { if (!_active.Remove(isbn, out Loan loan)) throw new InvalidOperationException("Not on loan."); int daysLate = Math.Max(0, day - loan.DueDay); decimal fine = daysLate * FinePerDay; if (fine > 0) _fines.Add((loan.Member, fine)); BookReturned?.Invoke(loan, day, fine); } public IEnumerable<Loan> Overdue(int today) => _active.Values.Where(l => today > l.DueDay).OrderBy(l => l.DueDay); public IEnumerable<(string Name, decimal Total)> FinesByMember() => _fines.GroupBy(f => f.Member.Name) .Select(g => (g.Key, g.Sum(f => f.Amount))) .OrderBy(x => x.Key); public IEnumerable<Book> Available() => _books.Values.Where(b => !_active.ContainsKey(b.Isbn)); } class ActivityLog { public void OnLent(Loan loan) => Console.WriteLine(
quot;[day {loan.Day,2}] {loan.Member.Name} borrowed '{loan.Book.Title}', due day {loan.DueDay}"); public void OnReturned(Loan loan, int day, decimal fine) => Console.WriteLine(
quot;[day {day,2}] {loan.Member.Name} returned '{loan.Book.Title}'" + (fine > 0 ?
quot;, fine {fine:F2}" : "")); }
[day  1] Alice borrowed 'Dune', due day 15
[day  3] Bob borrowed 'The Hobbit', due day 17
[day  5] Alice borrowed '1984', due day 19
[day 12] Alice returned 'Dune'
[day 24] Bob returned 'The Hobbit', fine 1.75

== Report on day 30 ==
OVERDUE  1984 (Alice), due day 19
Fines    Bob: 1.75
On shelf Dune, The Hobbit, Emma

Ideas for extending the project

Try these on your own computer, where you can read real input:

  1. Interactive menu — wrap the actions in a do..while loop that reads commands with Console.ReadLine() and a switch on the command name.
  2. Persistence — save books and loans to a CSV or JSON file (System.Text.Json.JsonSerializer) when the program exits and load them at start-up.
  3. Reservations — let members reserve a book that is on loan, using a Queue<Member> per book; when the book is returned, lend it to the next member in the queue automatically.
  4. Real dates — replace day numbers with DateOnly values and compute lateness with DayNumber differences.
  5. Unit tests — create an xUnit test project (dotnet new xunit) and test the rules: lending a lent book must throw, students may borrow only one book, fines are calculated correctly.

Test yourself

Why are the library's dictionaries declared private?

  1. Private fields are faster
  2. So other code can only change the data through methods that enforce the rules
  3. Dictionaries cannot be public
  4. To make them static

What does _active.Remove(isbn, out Loan loan) do?

  1. Removes all loans
  2. Removes the entry and outputs its value, returning false if the key is missing
  3. Only checks whether the key exists
  4. Throws if the key exists

What is the benefit of raising BookLent as an event instead of calling ActivityLog directly?

  1. Events are faster than method calls
  2. The library does not depend on the log; any number of listeners can subscribe
  3. Events run on a background thread
  4. It is required for records