Search This Blog

Monday, December 23, 2013

IEquatable C# Example

C# > System > Interfaces > IEquatable

IEquatable<T> Interface defines Equals method for determining equality of instances.
Example

public class Car : IEquatable<Car>
{
            public int Power { get; set; }
       public bool Equals(Car other)
       {
              if (other == null)
                    return false;
              if(this.Power == other.Power)
                    return true;
              return false;
       }
       public override bool Equals(Object obj)
       {
              if (obj == null)
                    return false;
              Car carObj = obj as Car;
              if (carObj == null)
                    return false;
              else
                    return Equals(carObj);
       }  
}

Car c1 = new Car();
c1.Power = 100;
Car c2 = new Car();
c2.Power = 100;
if (c1.Equals(c2))
    System.Windows.MessageBox.Show("Same power");