C#
Business logic
Write business rules with methods and conditional logic.
AddBook and ListBooks methods
We will move the add and list operations into methods. The AddBook(string title, int pageCount) method creates a new Book and adds it to the books list. The ListBooks() method uses a foreach loop to print every book in the list.
Giving methods parameters makes the code more flexible, because you can call the same method with different titles and page counts. The foreach loop is the easiest way to walk through all elements of a list. In this lesson we will define both methods and use them in Main.
Iterating the list with foreach
Inside the ListBooks method, the foreach (Book b in books) loop assigns each book in turn to the variable b. In the loop body we access the book's details with b.Title and b.PageCount.
For example, foreach (Book b in books) { Console.WriteLine(b.Title + " - " + b.PageCount + " pages"); } prints each book on a new line. foreach is a safe and short way to walk through all elements without knowing the list's length.
Exercise Add AddBook and ListBooks
Define the AddBook(string title, int pageCount) method; inside it add a book with books.Add(new Book { Title = title, PageCount = pageCount });. Define the ListBooks() method; use foreach (Book b in books) to print each book with Console.WriteLine(b.Title + " - " + b.PageCount + " pages");. In Main, add AddBook("The Lord of the Rings", 350); and AddBook("Crime and Punishment", 700);, then call ListBooks();.
Show example solution
Define AddBook and ListBooks methods, add two AddBook calls and ListBooks(); in Main.
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 AddBook(string title, int pageCount)
{
books.Add(new Book { Title = title, PageCount = pageCount });
}
static void ListBooks()
{
foreach (Book b in books)
{
Console.WriteLine(b.Title + " - " + b.PageCount + " pages");
}
}
static void Main()
{
AddBook("The Lord of the Rings", 350);
AddBook("Crime and Punishment", 700);
ListBooks();
}
}
Test yourself
-
What are the parameters of AddBook?
static void AddBook(string title, int pageCount)
- only title
- only pageCount
- title and pageCount
- books
Show answer
title and pageCount — Correct! AddBook takes two parameters: title and pageCount.
-
Match each method with its job
- AddBook
- Adds a book
- ListBooks
- Prints books
- foreach
- Iterates the list
-
foreach loop
foreach (Book b ____ books)
{
Console.WriteLine(b.Title);
}
Show answer
foreach (Book b in books)
{
Console.WriteLine(b.Title);
}
Next lesson: Error handling