The most likely scenario is that your search by code is failing and returning null. You should check for this explicitly.
while (itm.item == null)
{
Console.WriteLine("Enter the code :");
itm.item = searchItem(Convert.ToInt32(Console.ReadLine()));
if (itm.item == null)
{
Console.WriteLine("Item not found. Try again.");
}
}
Some additional notes:
- Normally public fields are frowned on. If they need to be public, it's better to make them properties in case you want to change the implementation later.
- I think the
SelectedItems class should calculate it's own subtotal rather than having it set externally.
- When you're dealing with money, you should either be using a custom
Money class or, at least, decimal values rather than double. Using decimal, because it's fixed point arithmetic is typically better than using a double (or float) so that you're not dealing with fractional cents.
Example:
public class SelectedItems
{
public Item Item { get; set; }
public int Quantity { get; set; }
public decimal Subtotal
{
get
{
if (Item == null)
{
return 0m;
}
return Item.UnitPrice * Quantity; /* unit price should be decimal */
}
}
}
You'd probably also want to add some validation or business rule checking, for example, the quantity must be 0 or greater.