I have three classes; Stamp, Letter and Parcel that implement an interface IProduct and they also have some of their own functionality.
public interface IP
This is because you are casting each Item in the shopping cart as IProduct in your foreach loop. What you would need to do is something like:
foreach(IProduct product in ShoppingCart.Items)
{
if (product is Stamp)
{
var stamp = product as Stamp;
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, UnitPrice: {3}", stamp.Name, stamp.Quantity, stamp.Amount, stamp.UnitPrice);
}
else if (product is Letter)
{
var letter = product as Letter;
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, Weight: {3}, Destination: {4}", letter.Name, letter.Quantity, letter.Amount, letter.Weight, letter.Destination);
}
else if (product is Parcel)
{
var parcel = product as Parcel;
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, Weight: {3}, Destination: {4}, Size: {5}", parcel.Name, parcel.Quantity, parcel.Amount, parcel.Weight, parcel.Destination, parcel.Size);
}
}
Alternatively, this more modern syntax now available in C#, which combines the is operator with the variable declaration:
foreach(IProduct product in ShoppingCart.Items)
{
if (product is Stamp stamp)
{
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, UnitPrice: {3}", stamp.Name, stamp.Quantity, stamp.Amount, stamp.UnitPrice);
}
else if (product is Letter letter)
{
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, Weight: {3}, Destination: {4}", letter.Name, letter.Quantity, letter.Amount, letter.Weight, letter.Destination);
}
else if (product is Parcel parcel)
{
Console.WriteLine("Name: {0}, Quantity: {1}, Amount: {2}, Weight: {3}, Destination: {4}, Size: {5}", parcel.Name, parcel.Quantity, parcel.Amount, parcel.Weight, parcel.Destination, parcel.Size);
}
}
Also you are repeating unnecessary properties Name, Quantity and Amount. You should derive each of your classes from Product:
public class Stamp: Product, IProduct
{
public double UnitPrice { get; set; }
}
public class TransitProduct: Product, IProduct
{
public double Weight { get; set; }
public string Destination { get; set; }
}
public class Letter: TransitProduct, IProduct
{
}
public class Parcel: TransitProduct, IProduct
{
public double Size { get; set; }
}