CodeBlanks Logo Icon CodeBlanks

Cart design

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.

Practice 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.

Starter code

Program.cs
using System;

// Define the Product class here

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

Sample solution

Program.cs
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);
    }
}

Expected output

Pen

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which data structure fits a cart best?

Program.cs
// several products in a cart
  • A single int variable
  • A list holding Product objects Correct answer
  • A single string variable
  • A bool variable

Explanation: You hold several Product objects in a List<Product>.

2 Write the class name

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

Explanation: Class names are PascalCase and start with a capital letter.

3 Match each property name to its type

Term Meaning
Name string
Price double
Quantity int
items List<Product>

All lessons in Beginner