Start learning free

LESSON 66 OF 69 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in C#: Two Classes with Composition

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • Public fields string name, double price, int quantity.
  • LineItem(string name, double price, int quantity) stores the three values with this..
  • double Subtotal() returns price * quantity.

Cart

  • It keeps its items in private List<LineItem> items = new List<LineItem>().
  • void Add(LineItem item) appends the item to the list.
  • double Total() returns the sum of the subtotals of all items: start double sum = 0, foreach over the items, return sum.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

Method names start with a capital letter in C#. The driver lives in Solution.MainFunction(); Console.WriteLine prints the double 75 as 75.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

class Solution {
    public void MainFunction() {
        Cart empty = new Cart();
        Console.WriteLine("Empty: " + empty.Total());
        LineItem apple = new LineItem("Apple", 5, 3);
        Console.WriteLine("Subtotal: " + apple.Subtotal());
        Cart cart = new Cart();
        cart.Add(apple);
        cart.Add(new LineItem("Bread", 20, 3));
        Console.WriteLine("Total: " + cart.Total());
        cart.Add(new LineItem("Milk", 10, 2));
        Console.WriteLine("Total: " + cart.Total());
    }
}

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write LineItem (fields, constructor, Subtotal) first, then Cart.

foreach (var item in items) sum += item.Subtotal();

class LineItem {
    public string name;
    public double price;
    public int quantity;

    public LineItem(string name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public double Subtotal() {
        return price * quantity;
    }
}

class Cart {
    private List<LineItem> items = new List<LineItem>();

    public void Add(LineItem item) {
        items.Add(item);
    }

    public double Total() {
        double sum = 0;
        foreach (var item in items) sum += item.Subtotal();
        return sum;
    }
}

class Solution {
    public void MainFunction() {
        Cart empty = new Cart();
        Console.WriteLine("Empty: " + empty.Total());
        LineItem apple = new LineItem("Apple", 5, 3);
        Console.WriteLine("Subtotal: " + apple.Subtotal());
        Cart cart = new Cart();
        cart.Add(apple);
        cart.Add(new LineItem("Bread", 20, 3));
        Console.WriteLine("Total: " + cart.Total());
        cart.Add(new LineItem("Milk", 10, 2));
        Console.WriteLine("Total: " + cart.Total());
    }
}

STEP 1 OF 18
    Ctrl + Enter to check

    C# · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in C#, explained

    Problem overview

    A shop keeps its orders in a cart. You build two classes that work together. A LineItem is one row of the cart: a product name, a price and a quantity. A Cart holds many rows and adds them up.

    LineItem has three public fields, string name, double price and int quantity, a constructor that stores them, and a method Subtotal() returning price * quantity. Cart keeps a private List<LineItem> items, adds rows with Add(LineItem item), and reports Total(), the sum of all subtotals.

    In the driver, an apple at price 5 with quantity 3 has a subtotal of 15. A cart holding the apple and bread at price 20 with quantity 3 totals 75. After a milk row (price 10, quantity 2) is added, the same cart's next total is 95. An empty cart totals 0.

    Approach: a cart has rows

    The relationship is composition. A cart has line items; it is not one, so it doesn't inherit from LineItem. It simply holds them in a list.

    The cart also doesn't know how a row computes its cost. It asks each row for Subtotal() and adds up the answers. If rows later priced themselves differently, Total() would not change.

    The total is computed each time it is requested, not stored. That is why adding the milk row changes the next total without any extra bookkeeping.

    Step by step

    1. Declare LineItem. The driver's new LineItem(...) builds objects from it.
    2. Add the public field name, a string.
    3. Add price, a double, in case a price isn't a whole number.
    4. Add quantity, an int, because how many were bought is always whole.
    5. Write the constructor. It is named LineItem, like the class, and has no return type. It takes name, price and quantity.
    6. Store the name with this.name = name;. The parameter and the field share a name, so this. tells C# which one is the field.
    7. Store the price the same way.
    8. Store the quantity the same way.
    9. Add Subtotal, a public method returning double.
    10. Return price * quantity. Both are fields of this row, so no this. is needed.
    11. Declare Cart below LineItem.
    12. Add the private field items, a List<LineItem> starting as a new empty list. Rows arrive one at a time, and a list grows as you add.
    13. Add the method Add, public and void, taking a LineItem named item.
    14. Call items.Add(item). The list keeps rows in the order they came in.
    15. Add Total, a public method returning double. Its body takes three lines.
    16. Start double sum = 0;. A running total starts at zero, so an empty cart gives 0.
    17. Loop with foreach over items and add each row's Subtotal() to sum. foreach hands you each element in turn, so you need no index.
    18. Return sum once, after the loop.

    The solution in C#

    class LineItem {
        public string name;
        public double price;
        public int quantity;
    
        public LineItem(string name, double price, int quantity) {
            this.name = name;
            this.price = price;
            this.quantity = quantity;
        }
    
        public double Subtotal() {
            return price * quantity;
        }
    }
    
    class Cart {
        private List<LineItem> items = new List<LineItem>();
    
        public void Add(LineItem item) {
            items.Add(item);
        }
    
        public double Total() {
            double sum = 0;
            foreach (var item in items) sum += item.Subtotal();
            return sum;
        }
    }
    
    class Solution {
        public void MainFunction() {
            Cart empty = new Cart();
            Console.WriteLine("Empty: " + empty.Total());
            LineItem apple = new LineItem("Apple", 5, 3);
            Console.WriteLine("Subtotal: " + apple.Subtotal());
            Cart cart = new Cart();
            cart.Add(apple);
            cart.Add(new LineItem("Bread", 20, 3));
            Console.WriteLine("Total: " + cart.Total());
            cart.Add(new LineItem("Milk", 10, 2));
            Console.WriteLine("Total: " + cart.Total());
        }
    }
    

    The driver prints:

    Empty: 0
    Subtotal: 15
    Total: 75
    Total: 95
    

    C# details

    • Constructor and methods. The constructor LineItem has no return type. Cart.Add is an ordinary method that shares its name with List.Add, but inside it items.Add(item) is a call on the list, so it does not call itself.
    • var in foreach. foreach (var item in items) lets the compiler infer that item is a LineItem. Writing LineItem item would mean the same.
    • Mixed arithmetic. price * quantity multiplies a double by an int; the int is converted, and the result is a double.
    • Printing doubles. A double holding 75 prints as 75, which is why the output has no decimal point.
    • Rows are shared objects. LineItem is a class, so the cart stores a reference to the same object the caller has. If the caller sets apple.quantity = 10 after adding it, the cart's next total counts 10 apples. In the driver's cart that turns the total of 95 into 130.

    Complexity

    Add is O(1) on average. Total visits every row once, so it takes O(n) time for n rows and O(1) extra space. The cart itself uses O(n) space for its rows.

    Edge cases and common mistakes

    • Empty cart. The loop never runs and sum stays 0.
    • Storing the total. Keeping a total field and updating it in Add works until a row changes. Computing it in Total() always matches the current rows.
    • Declaring sum inside the loop. It would restart at 0 for every row, and the return would not compile because sum would be out of scope.
    • Forgetting this. in the constructor. name = name; assigns the parameter to itself and leaves the field empty. The compiler only warns about it.
    • Decimal prices. They work, but doubles are approximate: a price of 0.1 with quantity 3 gives 0.30000000000000004. A price of 2.5 with quantity 3 gives 7.5. The lesson's driver uses whole numbers.

    Testing

    • A cart holding only the apple (5 times 3) gives a total of 15.
    • The same row added twice to one cart counts twice. With the apple at quantity 10 added twice the total is 100.
    • A row of price 2.5 and quantity 3 has a subtotal of 7.5.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free