OOP model
Set up the class hierarchy and interfaces.
The Library class
A Library class holds books together. It stores an inner List<Book> and accepts new books via an Add method. A Count property tells how many books it has.
This design is an example of encapsulation: the outside cannot reach the inner list directly; it works only through controlled members like Add and Count. The data stays safe inside the class.
Add and Count members
public void Add(Book b) => _books.Add(b); adds a new book with a single expression body. public int Count => _books.Count; exposes the list's count to the outside.
These members are called from outside; the _books field is private and cannot be reached directly. This is the practical payoff of encapsulation: internal changes do not break external code.
Exercise Add the Library class
The Book class below is ready. Add a Library class: it holds an inner List<Book> _books and exposes Add(Book b) and Count. In Main create a Library, add a book and print the count.
Show example solution
Write class Library { private List<Book> _books = new List<Book>(); public void Add(Book b) => _books.Add(b); public int Count => _books.Count; }. In Main write var lib = new Library(); lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" }); Console.WriteLine(lib.Count);
Example solution:
using System;
using System.Collections.Generic;
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;
}
class Program
{
static void Main()
{
var lib = new Library();
lib.Add(new Book { Title = "Crime and Punishment", Author = "Dostoevsky" });
Console.WriteLine(lib.Count);
}
}
Test yourself
-
Complete the list declaration
private List<____> _books = new List<Book>();Show answer
private List<Book> _books = new List<Book>(); -
Why is _books private?
- It runs faster
- It provides encapsulation
- The compiler requires it
- The garbage collector needs it
Show answer
It provides encapsulation — Correct. private access shields the inner list from outside tampering.
-
Match the member to its role
- _books
- Inner list
- Add
- Add a book
- Count
- Book tally
- private
- Hidden access