C#
Data model
Set up the data model and collections for the app.
Book class and book list
In the book list app, we will define a Book class to represent each book. This class will have two fields: Title and PageCount. We will also use a List<Book> to hold all the books.
List<T> is a collection that provides a dynamic array in C#. It comes with the using System.Collections.Generic; directive. You add items with the Add method and access them with [index]. In this lesson we will add the Book class, a static list called books, and the first book.
Sharing with a static field
We will keep the book list as static List<Book> books at the class level. This way, methods like AddBook and ListBooks can easily access the list. A static field is shared across all instances of the class; for our small program, a single list is enough.
For example, static List<Book> books = new List<Book>(); creates an empty list when the program starts. Then we add books with books.Add(new Book { ... }). This structure lets methods share the list in later lessons.
Exercise Add the Book class and list
Add using System.Collections.Generic; at the top. Define a Book class with public string Title; and public int PageCount; fields. Add a static List<Book> books = new List<Book>(); field to the Program class. In Main, add a book with books.Add(new Book { Title = "The Lord of the Rings", PageCount = 350 });, then print it with Console.WriteLine(books[0].Title + " - " + books[0].PageCount + " pages");. Keep the PrintMenu(); call at the end.
Show example solution
Add using System.Collections.Generic;, define class Book { public string Title; public int PageCount; }, add static List<Book> books = new List<Book>();, in Main use books.Add and WriteLine to print the book.
Example solution:
using System;
using System.Collections.Generic;
class Book
{
public string Title;
public int PageCount;
}
class Program
{
static List<Book> books = new List<Book>();
static void PrintMenu()
{
Console.WriteLine("1 - Add");
Console.WriteLine("2 - List");
Console.WriteLine("3 - Exit");
}
static void Main()
{
books.Add(new Book { Title = "The Lord of the Rings", PageCount = 350 });
Console.WriteLine(books[0].Title + " - " + books[0].PageCount + " pages");
PrintMenu();
}
}
Test yourself
-
Match each field with its type
- Title
- string
- PageCount
- int
- List<Book>
- book collection
-
Which using is needed for List<T>?
List<Book> books = new List<Book>();
- System.Text
- System.Collections.Generic
- System.IO
- System.Linq
Show answer
System.Collections.Generic — Correct! List<T> lives in System.Collections.Generic.
-
Book class declaration
class Book
{
____ string Title;
public int PageCount;
}
Show answer
class Book
{
public string Title;
public int PageCount;
}
Next lesson: Business logic