CodeBlanks Logo Icon CodeBlanks

Adding products

C# course · Beginner · Lesson 49/116

Learn to add products to the cart with the AddProduct method.

Adding products

The Product class is ready; now we will write an AddProduct method to add items to the cart. The Cart class already has a private List<Product> items field; this list holds the added products.

The AddProduct(Product product) method calls items.Add(product) in its body. Each new product is then appended to the end of the list. The method returns no value, so its type is void.

List<T> and adding

List<T> is C#'s flexible array structure; its size grows automatically. items.Add(x) appends x, items.Count gives the count, and items[i] accesses by index.

You must initialize a List with new List<Product>() before using it; otherwise you get a null error. In the Cart class this is already done by private List<Product> items = new List<Product>();.

Exercise Write the AddProduct method

Add an AddProduct method inside the Cart class. Its signature must be public void AddProduct(Product product). The body should call items.Add(product);. Main already adds a product and prints 'added'.

Show example solution
Inside the Cart class write public void AddProduct(Product product) { items.Add(product); }
Example solution:
using System;
using System.Collections.Generic;

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

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

    public void AddProduct(Product product)
    {
        items.Add(product);
    }
}

class Program
{
    static void Main()
    {
        var cart = new Cart();
        cart.AddProduct(new Product { Name = "Notebook", Price = 25, Quantity = 1 });
        Console.WriteLine("added");
    }
}

Test yourself

  1. What does cart.AddProduct(new Product {...}) do?

    cart.AddProduct(new Product { Name = "Notebook", Price = 25, Quantity = 1 });
    • Removes a product from the cart
    • Computes the total
    • Updates the quantity
    • Adds a product to the cart
    Show answer

    Adds a product to the cart — Correct. AddProduct appends a new Product object to the cart list.

  2. Write the items.Add call

    public void AddProduct(Product product)
    {
        ____(product);
    }
    Show answer
    public void AddProduct(Product product)
    {
        items.Add(product);
    }
  3. Match each method to its job

    AddProduct
    Adds to the cart
    RemoveProduct
    Removes from the cart
    UpdateQuantity
    Changes the quantity
    GetSubtotal
    Returns the subtotal

All lessons in Beginner