Reputation: 13
When a product is sold my intended behaviour is for productSold in ProductManagement to call inventory.UpdateProduct()
and dynamically update inventory.
I've applied some breakpoints and found when p.productSold(p1) is called, it never actually enters inventory.UpdateProduct()
and so inventory is never updated.
To play around with this I've explicitly called the method in main inv.UpdateProduct(item id, quantity)
and it seems to be working however, I would like UpdateProduct to be called when productSold is.
class Program
{
static void Main(string[] args)
{
// Products
Product p1 = new Product(1, 20, 1000);
// Inventory
Inventory inv = new Inventory();
ProductManagement p = new ProductManagement();
// Add Products to inventory
inv.AddProduct(p1);
// Products sold
p.productSold(p1);
//inv.UpdateProduct(1,50);
// View Inventory
inv.ViewInventory();
Console.ReadLine();
}
}
class Product
{
public int _id;
public int _price;
public int _quantity;
public Product(int id, int price, int quantity)
{
_id = id;
_price = price;
_quantity = quantity;
}
}
class Inventory
{
private List<Product> inventory = new List<Product>();
public Inventory()
{
}
public void AddProduct(Product product)
{
inventory.Add(product);
}
public void UpdateProduct(int id, int quantity)
{
foreach(Product p in inventory)
{
if (p._id == id)
{
Console.WriteLine("product found");
p._quantity -= quantity;
}
else
{
Console.WriteLine("cannot find product");
}
}
/* var product = inventory.Single(x => x._id == id);
product._quantity -= quantity; */
}
public void ViewInventory()
{
foreach(Product p in inventory)
{
Console.WriteLine("Item ID : {0} Item Price : {1} Item Quantity : {2}", p._id, p._quantity, p._quantity);
}
}
}
class ProductManagement
{
public Inventory inventory = new Inventory();
public void productSold(Product product)
{
var quantitySold = 1;
inventory.UpdateProduct(product._id, quantitySold);
}
}
Upvotes: 1
Views: 46
Reputation: 438
The "Inventory" inside your "ProductManagement" isn't the same inventory you have in your Main function.
You can make the following changes to your ProductManagement: (Add a constructor with parameter)
public class ProductManagement
{
public Inventory inventory;
public ProductManagement(Inventory inv)
{
this.inventory = inv;
}
public void productSold(Product product)
{
var quantitySold = 1;
inventory.UpdateProduct(product._id, quantitySold);
}
}
Change your Main as follows:
static void Main(string[] args)
{
Product p1 = new Product(1, 20, 1000);
Inventory inv = new Inventory();
ProductManagement p = new ProductManagement(inv); //THE CHANGE
inv.AddProduct(p1);
p.productSold(p1);
inv.ViewInventory();
Console.ReadLine();
}
Upvotes: 2