The requested page is not available for the requested platform. You are viewing the content for Default platform.

Implement IEquatable

Purpose

Using this Code Provider, you can easily add the implementation of the IEquatable<T> interface to any class containing at least one field or property. This Code Provider adds the IEquatable<T> implementation along with all required overloads (two overloads of the Equals method, GetHashCode method, == (= in VB) operator and != (<> in VB) operator) to the class.

Availability

Available when the caret is on a class declaration.

Usage

  1. Place the caret on a class declaration. The class must contain at least one field or property.

    Note

    The blinking cursor shows the caret's position at which the Code Provider is available.

    public class Temperature {
        protected double temperatureF;
        public double Fahrenheit {
            get {
                return this.temperatureF;
            }
            set {
                this.temperatureF = value;
            }
        }
        public double Celsius {
            get {
                return (this.temperatureF - 32) * (5.0 / 9);
            }
            set {
                this.temperatureF = (value * 9.0 / 5) + 32;
            }
        }
    }
    
  2. Use the Ctrl + . or Ctrl + ~ shortcut to invoke the Code Actions Menu.
  3. Select Implement IEquatable from the menu.

After execution, the Code Provider adds the implementation of the IEquatable<T> interface. It also adds the corresponding overloads of methods and operators with their common implementation.

public class Temperature : IEquatable<Temperature> {
    protected double temperatureF;
    public double Fahrenheit {
        get {
            return this.temperatureF;
        }
        set {
            this.temperatureF = value;
        }
    }
    public double Celsius {
        get {
            return (this.temperatureF - 32) * (5.0 / 9);
        }
        set {
            this.temperatureF = (value * 9.0 / 5) + 32;
        }
    }

    public override bool Equals(object obj) {
        if (obj is Temperature)
            return Equals((Temperature)obj);
        return base.Equals(obj);
    }

    public static bool operator ==(Temperature first, Temperature second) {
        if ((object)first == null)
            return (object)second == null;
        return first.Equals(second);
    }

    public static bool operator !=(Temperature first, Temperature second) {
        return !(first == second);
    }

    public bool Equals(Temperature other) {
        if (ReferenceEquals(null, other))
            return false;
        if (ReferenceEquals(this, other))
            return true;
        return this.temperatureF.Equals(other.temperatureF);
    }

    public override int GetHashCode() {
        unchecked {
            int hashCode = 47;
            hashCode = (hashCode * 53) ^ temperatureF.GetHashCode();
            return hashCode;
        }
    }
}
See Also