0

I have an issue that's been bothering me.

I have an assignment to do which involves creating a program that does several tasks, using OOP.

The assignment is creating a shopping cart using separate classes and one of the tasks is to eliminate one item from the class.

I have it set it up like this.

Product class is:

class Product
{
    private string name;
    private decimal price;

    public Product(string name, decimal price)
    {
        this.name = name;
        this.price = price;
    }

Shopping cart class is:

class ShoppingCart
{
    private Product[] products;

    public ShoppingCart(Product[] products)
    {
        this.products = products;
    }

To remove the last item, I'm trying this within the ShoppingCart class.

public void RemoveLastProductFromCart()
{
   Array.Resize(ref products, products.Length - 1);
}

But it's not resizing the Product[] products and I cannot find another way to do so. I have to use arrays because we haven't gotten to lists yet.

EDIT: This is the test I have to check if the resizing works, and the function is called:

        [TestMethod]
    public void ShouldRemoveLastProductInCart()
    {
        Product[] products =
        {
          new Product("Milk", 12.10m),
          new Product("Meat", 14.15m)
        };

        ShoppingCart cart = new ShoppingCart(products);
        cart.RemoveLastProductFromCart();
        Assert.AreEqual(1, products.Length);
    }
Babak Naffas
  • 12,395
  • 3
  • 34
  • 49

1 Answers1

5

The problem is your test, once you called Array.Resize the array the products variable in ShouldRemoveLastProductInCart and the array in cart.products are no longer the same array in memory.

If you made your test check cart.products size you would see a correct value of 1.

Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431