Implement IComparable

  • 3 minutes to read

Purpose

Use this Code Provider to add the implementation of the IComparable interface to any type (for example, class and record) containing at least one field or property. This Code Provider adds the IComparable and IComparable<T> implementations along with the CompareTo methods to the type. The CompareTo method bodies are generated automatically.

Availability

Available when the caret is on a type declaration.

Usage

  1. Place the caret on a type declaration. The type 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. Press 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