Skip to main content

Implement IComparable

  • 2 minutes to read
In This Article

Implements the IComparable interface in the current class.

#Availability

From the context menus or via shortcuts:

  • when the edit cursor or caret is on a declaration of a class containing fields or properties, provided that the class does not implement IComparable.

#Example

public class MyClass
{
  public string StringValue { get; set; }
  public string IntValue { get; set; }
}
Public Class TestClass
  Public Property StringValue() As String
  Public Property IntValue() As String
End Class

Result:

public class MyClass : IComparable, IComparable<MyClass>
{
  public int CompareTo(object obj)
  {
    if(obj == null)
      return 1;
    MyClass other = obj as MyClass;
    if(other == null)
      throw new ArgumentException("obj is not a MyClass");
    return CompareTo(other);
  }
  public int CompareTo(MyClass other)
  {
    if(other == null)
      return 1;
    int result = 0;
    result = this.StringValue.CompareTo(other.StringValue);
    if(result != 0)
      return result;
    result = this.IntValue.CompareTo(other.IntValue);
    if(result != 0)
      return result;
    return result;
  }
  public string StringValue { get; set; }
  public string IntValue { get; set; }
}
Public Class TestClass
  Implements IComparable
  Implements IComparable(Of TestClass)
  Public Function CompareTo(ByVal obj As Object) As Integer Implements IComparable.CompareTo
    If obj Is Nothing Then
      Return 1
    End If
    Dim other As TestClass = IIf(TypeOf obj Is TestClass, CType(obj, TestClass), Nothing)
    If other Is Nothing Then
      Throw New ArgumentException("obj is not a TestClass")
    End If
    Return CompareTo(other)
  End Function
  Public Function CompareTo(ByVal other As TestClass) As Integer Implements IComparable(Of TestClass).CompareTo
    If other Is Nothing Then
      Return 1
    End If
    Dim result As Integer = 0
    result = Me.StringValue.CompareTo(other.StringValue)
    If result <> 0 Then
      Return result
    End If
    result = Me.IntValue.CompareTo(other.IntValue)
    If result <> 0 Then
      Return result
    End If
    Return result
  End Function
  Public Property StringValue() As String
  Public Property IntValue() As String
End Class