Implement IComparable

Purpose

Using this Code Provider, you can easily add the implementation of the IComparable interface to any class containing at least one field or property. This Code Provider adds the IComparable and IComparable<T> implementations along with the CompareTo methods to the class. The CompareTo method bodies are generated automatically.

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 IComparable from the menu.

After execution, the Code Provider adds the implementation of the IComparable interface and type-specific IComparable<T> interface. It also adds the corresponding CompareTo methods with their common implementation.

public class Temperature : IComparable, IComparable<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 int CompareTo(object obj) {
        if (obj == null)
            return 1;
        Temperature other = obj as Temperature;
        if (other == null)
            throw new ArgumentException("obj is not a Temperature");
        return CompareTo(other);
    }

    public int CompareTo(Temperature other) {
        if (other == null)
            return 1;
        int result = 0;
        result = this.temperatureF.CompareTo(other.temperatureF);
        if (result != 0)
            return result;
        return result;
    }
}
See Also