C#


CSHARP.COMPARE.CTO.NONOBJ : Non-Object compareTo Parameter (C#)

要旨

CompareTo() is defined for a non-System.Object argument but the comparable class is raw.

A class C that implements the raw interface System.IComparable must implement the CompareTo(Object) method. If C is made to implement the non-raw interface System.IComparable<C>, then it must implement the CompareTo(C) method instead.

Moreover, it is good practice to make CompareTo() consistent with Equals(): if the comparison of two objects yields 0, then they should be equal. The validity of this implication is in general undecidable. There are, however, frequent situations when, typically, this implication does not hold. An example is when Equals() is inherited from System.Object.

This checker verifies that CompareTo(Object) is defined for classes implementing the raw System.IComparable interface, instead of the (possibly more logical) method CompareTo(C). Moreover, it verifies the consistency of CompareTo() wrt Equals().

Inconsistent definitions of CompareTo()/Equals() induce unexpected behaviors when objects are put inside most sorted collection classes of the standard .NET library.

プロパティ

クラス名 Non-Object compareTo Parameter (C#)
日本語クラス名 Non-Object compareTo Parameter (C#)
クラス分類 信頼性 (reliability)
ニーモニック CSHARP.COMPARE.CTO.NONOBJ
カテゴリー
CWE CWE:1097 Persistent Storable Data Element without Associated Comparison Control Element
対応言語 C# で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Non-Object compareTo Parameter (C#)"

public abstract class CompareTo : IComparable<CompareTo> {
  private static int nextId;
  private final int id = nextId++;

  public final int compareTo(CompareTo other) {  // "Non-Object compareTo Parameter (C#)" warning issued here
  {
    return id - other.id;
  }
}

解決法

Use the non-raw interface System.IComparable<C>; make Equals() consistent with CompareTo(). In most cases, this just amounts to providing the missing definition of Equals().

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。