CodeBlanks Logo Icon CodeBlanks

Cart design

C# course · Beginner · Lesson 48/116

Design the shopping cart class skeleton and the product model.

Cart design

In this project we will build a shopping cart application step by step. The first step is to design the Product class that represents an item in the cart.

A product has three core properties: name (string), price (double) and quantity (int). In C# we write these as auto properties using public ... { get; set; }. They can then be accessed as p.Name from outside.

Auto property

In C#, writing public string Name { get; set; } creates an auto property. The compiler generates a hidden field behind the scenes; you do not write the get/set body.

This is very handy for classes that simply carry data. You can build the object shortly with var p = new Product { Name = "Pen", Price = 12.5, Quantity = 2 };; this form is called an object initializer.

Exercise Define the Product class

Define a Product class. It must have three auto properties: public string Name, public double Price, public int Quantity (each with { get; set; }). Main already builds a Product and prints its name; you only write the class.

Show example solution
Write class Product and add three auto properties inside.
Example solution:
using System;

class Product
{
    public string Name { get; set; }
    public double Price { get; set; }
    public int Quantity { get; set; }
}

class Program
{
    static void Main()
    {
        var p = new Product { Name = "Pen", Price = 12.5, Quantity = 2 };
        Console.WriteLine(p.Name);
    }
}

Test yourself

  1. Which data structure fits a cart best?

    // several products in a cart
    • A single int variable
    • A single string variable
    • A list holding Product objects
    • A bool variable
    Show answer

    A list holding Product objects — Correct. You hold several Product objects in a List<Product>.

  2. Write the class name

    class ____
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
    }
    Show answer
    class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
    }
  3. Match each property name to its type

    Name
    string
    Price
    double
    Quantity
    int
    items
    List<Product>

All lessons in Beginner