LoginSignup
9
0

ListのオブジェクトをRemoveで削除しようとしたらできなかった話

Last updated at Posted at 2023-12-19

初めに

C#でテスト用のツールを作成している際に、想定していない結果になったので処理を追ってみたところ、あるList要素の削除に失敗していることがわかりました。

原因

このListに格納していたのは独自に定義したクラスです。
このクラス定義にて、等価性に関する記述が抜けていたために、Listで削除対象のオブジェクトを評価することができていませんでした。

解決方法

以下のように、等価性をチェックする処理を追記します。

public class MyClass
{
    public int Value { get; }

    public MyClass(int value)
    {
        this.Value = value;
    }

    // 追記
    public bool Equals(MyClass other)
    {
        if (ReferenceEquals(null, other)) return false;
        if (ReferenceEquals(this, other)) return true;
        return Value == other.Value;
    }
    
    // 追記
    public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((MyClass)obj);
    }

    // 追記
    public override int GetHashCode()
    {
        return Value.GetHashCode();
    }
}

終わりに

見つけるのが一苦労なバグを生み出してしまうので、今後繰り返さないように注意したいです。

9
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
0