c#,override,equality,semantics

Erhan 8/16/2016 0

This Code Shows How to Override Equality Semantics

C#
 public struct Area : IEquatable <Area>
{
  public readonly int Measure1;
  public readonly int Measure2;

  public Area (int m1, int m2)
  {
    Measure1 = m1;
    Measure2 = m2;
  }

  public override bool Equals (object other)
  {
    if (!(other is Area)) return false;
    return Equals ((Area) other);        // Calls method below
  }

  public bool Equals (Area other)        // Implements IEquatable<Area>
  {
    return Measure1 == other.Measure1 && Measure2 == other.Measure2
        || Measure1 == other.Measure2 && Measure2 == other.Measure1;
  }

  public override int GetHashCode()
  {
    if (Measure1 > Measure2)
      return Measure1 * 37   Measure2;    // 37 = a prime number
    else
      return Measure2 * 37   Measure1;
  }

  public static bool operator == (Area a1, Area a2)
  {
     return a1.Equals (a2);
  }

  public static bool operator != (Area a1, Area a2)
  {
    return !a1.Equals (a2);
  }
} 

Report Bug

Please Login to Report Bug

Reported Bugs

Comments

Please Login to Comment

Comments