I am new to the language C# and I am trying to figure out how I can get my Quantity
property to calculate the final price by multiplying the quantity of items bought and then the item price of 12.35 anytime the quantity ordered is set.
I am also having a problem with using the Equals()
method. I am trying to use the Equals()
method to compare 2 orders based on their order number but I am receiving a warning in my Visual Studio saying that 'Order' overrides Object.Equals(object o) but does not override Object.GetHashCode()
. How do I fix this?
Here is my program:
using System;
namespace Order
{
class Program
{
static void Main(string[] args)
{
// creating the orders
Order order1 = new Order(1, "Joe Bob", 2);
Order order2 = new Order(3, "Sally Bob", 4);
Order order3 = new Order(1, "Jimmy Bob", 5);
Console.WriteLine(order1.ToString() + "\n");
Console.WriteLine(order2.ToString() + "\n");
Console.WriteLine(order3.ToString() + "\n");
//checks for duplicates
CheckDuplicate(order1, order2);
CheckDuplicate(order2, order3);
CheckDuplicate(order1, order3);
}
// output for duplicates
public static void CheckDuplicate(Order firstOrder, Order secondOrder)
{
if (firstOrder.Equals(secondOrder))
{
Console.WriteLine("The two orders are the same!");
}
else
{
Console.WriteLine("The two orders are not the same!");
}
}
}
class Order
{
// setting properties
public int OrderNum { get; set; }
public string CustomerName { get; set; }
public double Quantity;
private readonly double Total;
// total price
public double GetTotal()
{
double itemPrice = 12.35;
double Total = Quantity * itemPrice;
return Total;
}
// equals to method
public override bool Equals(Object o)
{
bool isEqual = true;
if (this.GetType() != o.GetType())
isEqual = false;
else
{
Order temp = (Order)o;
if (OrderNum == temp.OrderNum)
isEqual = true;
else
isEqual = false;
}
return isEqual;
}
// default constructor
public Order(int OrderNum, string CustomerName, double Quantity)
{
this.OrderNum = OrderNum;
this.CustomerName = CustomerName;
this.Quantity = Quantity;
}
// returns final output
public override string ToString()
{
return ("Order Number : " + OrderNum) + "\n" + ("Customer name : " + CustomerName) + "\n" + ("Quantity Ordered : " + Quantity) + "\n" + ("Totatl Price : " + Total);
}
}
}