0

I have created a class that represents the Fraction as shown below. I have found difficulty to understand the problem of equality between new objects. Could anyone explain me please why this happens;

   Fraction f1 = new Fraction(1, 2);
   Fraction f2 = new Fraction(1, 2);

   if (f1.Equals(f2)) Console.WriteLine("true"); // does not return anything

The Fraction Class

class Fraction: IComparable<Fraction>
{

    public int Numerator { get; set; }
    private int _denominator;

    public decimal Decimal
    {
        get { return (Decimal)Numerator / Denominator; }
        private set { }
    }
    public int Denominator
    {
        get { return _denominator; }
        set {
            if (value != 0)
                _denominator = value;
            else
                throw new Exception();

            }
    }

    public Fraction(int num, int den)
    {
        Numerator = num;
        Denominator = den;
    }

    public Fraction(int num)
    {
        Numerator = num;
        Denominator = 1;
    }

    public Fraction()
    {
    }

    public override string ToString()
    {
        return String.Format( "{0}/{1}", Numerator, Denominator);
    }

    public static Fraction operator *(Fraction f1, Fraction f2)
    {
        return new Fraction(f1.Numerator * f2.Numerator, f1.Denominator* f2.Denominator);
    }

    public static Fraction Parse(string str)
    {
        string[] parts = str.Split('/');
        if (parts.Length == 2)
            return new Fraction(Int32.Parse(parts[0]), Int32.Parse(parts[1]));
        else
            throw new Exception("Give a fraction in this form: \"1/4\" ");
    }

    public int CompareTo(Fraction other)
    {
        return this.Decimal.CompareTo(other.Decimal);
        //throw new NotImplementedException();
    }

}
  • 1
    You have not provided an implementation of Equals so the default equality operation is used which in this case is reference equality. – Mike Zboray May 06 '17 at 21:33
  • 2
    You call Equals but did not implement it. It is still using a reference compare. Instead of a class you might want to consider a struct – Emond May 06 '17 at 21:34
  • `IComparable` is used to define the behaviour of `>` and `<`. You need to override the `Equals` function. – Sumner Evans May 06 '17 at 21:37

0 Answers0