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);
    }
14
  • Arrays are fixed length by definition, aren't they? You can write a method that returns another array containing the remaining items of the previous array Commented Mar 10, 2016 at 21:52
  • Use List<Product> instead of array.... Commented Mar 10, 2016 at 21:53
  • @Eser Read the post. He has to use an array for this assignment Commented Mar 10, 2016 at 21:54
  • @ScottChamberlain I have to use arrays. I would very much like to use List, but not allowed yet. Commented Mar 10, 2016 at 21:55
  • 1
    It's dirty, but you could just create a new array and copy the contents of the initial array into the new shorter array. Commented Mar 10, 2016 at 21:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Damn. I really didn't see that. Thank you very much. Works now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.