LoginSignup
1
0

More than 1 year has passed since last update.

C#9のrecord型でEqualsの再定義

Posted at

C#で独自record同士の比較をしたかったが、ちょっと詰まったので、メモ

通常のrecordの場合

基本的にrecordは値型っぽく扱えるので、フィールドが値型であれば、特に何もしなくても値型の比較をしてくれる


record XXX(int Hoge);
Assert.AreEqual(new XXX(3), new XXX(3)); // true

recordのフィールドに参照型が混じった場合

この場合は、classの時と同様にちょっとコードを書く必要がある


record XXX(params int[] Hoges);
record YYY(params int[] Hoges) {
    public virtual bool Equals(YYY y) {
        if(y is null)  return false;
        return Hoges.SequenceEqual(y.Hoges);
    }
    public override int GetHashCode()
    {
        HashCode hashcode = new();
        foreach(var h in Hoges) {
            hashcode.Add(h);
        }
        return hashcode.ToHashCode();
    }
}
Assert.AreEqual(new XXX(3), new XXX(3)); // false
Assert.AreEqual(new YYY(3), new YYY(3)); // true

ポイントはEqualsはvirtualで定義するところ。なぜvirtualにするかは正直あんまり理解してない(調べてない)が、record型の都合なのだろうという解釈をとりあえずしている。

1
0
0

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
1
0