Adding products
- C# course
- Beginner
- Lesson 49/116
- 6 min
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>();.
Practice 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'.
Starter code
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>();
// Write the AddProduct method here
}
class Program
{
static void Main()
{
var cart = new Cart();
cart.AddProduct(new Product { Name = "Notebook", Price = 25, Quantity = 1 });
Console.WriteLine("added");
}
}Sample 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");
}
}Expected output
added
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
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
- Adds a product to the cart Correct answer
- Updates the quantity
Explanation: AddProduct appends a new Product object to the cart list.
2 Write the items.Add call
public void AddProduct(Product product)
{
____(product);
}
public void AddProduct(Product product)
{
items.Add(product);
}
Explanation: items.Add(product) appends the product to the list.
3 Match each method to its job
| Term | Meaning |
|---|---|
AddProduct |
Adds to the cart |
RemoveProduct |
Removes from the cart |
UpdateQuantity |
Changes the quantity |
GetSubtotal |
Returns the subtotal |