Shashank Shashank - 1 year ago 72
C# Question

Properties always return zero / null values

We have been given an assignment to develop a Shopping cart using C#
Which has Item (Properties: name, price)
ItemOrder(Properties: Item,Quantity)
I am trying to find out the net price of a product as price*quantity, but the price property always returns 0, I even tried printing the name and it appears a null
The quantity appears properly though.

Class Item

private string name;
private double price;

public string Name { get { return name; } set { name=value;} }
public double Price { get { return price; } set { price = value; } }
public Item()
Name =;
Price = this.price;
public Item(string name, double price)
Name = name;
Price = price;

Class ItemOrder : Item

private Item product;
private int quantity {get; set;}

public int Quantity { get {return quantity ;} set { quantity=value ;} }

public ItemOrder()
this.product.Name = Name;
this.product.Price = Price;
this.Quantity = Quantity;

public ItemOrder(Item product, int quantity)
Quantity = quantity;

Main Method:
The ItemOrders are properly added within the cart, and printed, But i am unable to access the price and name for calculations

List<Item> inventory = new List<Item>();
Item pancakes = new Item("Pancakes", 6.25);
List<ItemOrder> currentCart = new List<ItemOrder>();
ItemOrder item = new ItemOrder(inventory[userInput], quantity);
foreach (ItemOrder i in currentCart)
double currentPrice = 0;
currentPrice = (i.Price*.i.Quantity);
Console.WriteLine("(" + (currentCart.IndexOf(i) + 1) + ") : " + i.ToString() + "\t "+currentPrice);

Thanks in advance

Answer Source

Because of this line:

ItemOrder item = new ItemOrder(inventory[userInput], quantity);

You are calling this constructor:

public ItemOrder(Item product, int quantity)
    this.product = product;
    Quantity = quantity;

so the price that you're looking for is actually inside the product variable.

Try to add Product as a public property:

public Item Product { get {return product;} set { product=value ;} }

and replace this line:

currentPrice = (i.Price*.i.Quantity);

with this:

currentPrice = (i.Product.Price * i.Quantity);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download