CodeBlanks Logo Icon CodeBlanks

Model design

C# course · Intermediate · Lesson 65/116

Design the skeleton of Book and Member classes.

Project: Library app

In this 5-lesson project you will build a library app. Each lesson adds one piece, and by the final lesson you will have a working console program. You will write the data models first, then the management class, and finally the menu.

In this lesson you will define two core models: Book and Member. Each model is a class with auto-properties. A Book has a title, an author and a borrowed state; a Member has a name and a borrow count.

Creating instances with an object initializer

You can fill a class's properties right when you create the instance. This is called an object initializer. The expression new Book { Title = "The Hobbit", Author = "Tolkien" } creates a new Book and sets two properties.

This approach is more flexible than writing a parameterized constructor; you can skip any property you want. We will keep the models simple in this project and always use object initializers.

Exercise Define Book and Member classes

Define a Book class with auto-properties public string Title, public string Author, public bool IsBorrowed. Define a Member class with auto-properties public string Name, public int BorrowedCount. In Main create one instance of each and print the book's title and the member's name with Console.WriteLine.

Show example solution
Write class Book { public string Title { get; set; } public string Author { get; set; } public bool IsBorrowed { get; set; } }. Write class Member { public string Name { get; set; } public int BorrowedCount { get; set; } }. In Main create new Book { Title="The Hobbit", Author="Tolkien" } and new Member { Name="Alex" } and WriteLine them.
Example solution:
using System;

class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public bool IsBorrowed { get; set; }
}

class Member
{
    public string Name { get; set; }
    public int BorrowedCount { get; set; }
}

class Program
{
    static void Main()
    {
        var book = new Book { Title = "The Hobbit", Author = "Tolkien" };
        var member = new Member { Name = "Alex" };
        Console.WriteLine(book.Title);
        Console.WriteLine(member.Name);
    }
}

Test yourself

  1. How is an auto-property declared?

    • public string Title { get; set; }
    • string Title;
    • public string Title;
    • var Title = string;
    Show answer

    public string Title { get; set; } — Correct. get; set; declares an auto-property.

  2. Object initializer syntax

    var book = new Book ____ Title = "The Hobbit", Author = "Tolkien" };
    Show answer
    var book = new Book { Title = "The Hobbit", Author = "Tolkien" };
  3. Match each class piece to its job

    class
    Class template
    new
    Creates an instance
    public
    Access from anywhere
    string
    Text type

All lessons in Intermediate