Note: my case is for byte[] but I believe a good answer would work for any type.
Visual Studio's auto-generated implementation of Equals
uses EqualityComparer<T>.Default.Equals(T x, T y)
for reference types. I have a lot of classes with byte arrays that needs to be included in Equals
so I'd like to keep Visual studio's code if possible but Default
returns a ObjectEqualityComparer
for byte arrays. I've written a simple byte array comparer but I'm not sure how to proceed to have it used instead of ObjectEqualityComparer
.
public class Foo
{
public int Id {get;set;}
public byte[] Data {get;set;}
public override bool Equals(object obj)
{
var foo = obj as Foo;
return foo != null &&
Id == foo.Id &&
EqualityComparer<byte[]>.Default.Equals(Data, foo.Data);
}
}
static void Main
{
Foo f1 = new Foo { Id = 1, Data = new byte[1] { 0xFF } };
Foo f2 = new Foo { Id = 1, Data = new byte[1] { 0xFF } };
bool result = f1.Equals(f2); // false
}
public class ByteArrayComparer
{
public bool Equals(byte[] x, byte[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(byte[] obj)
{
return obj.GetHashCode();
// as Servy said, this is wrong but it's not the point of the question,
// assume some working implementation
}
}
Should ByteArrayComparer implement IEqualityComparer, inherit from EqualityComparer and override the methods, or something else?