You're right, this is a lot of boiler-plate code, and you need to implement everything separately.
I would recommend:
- If you're going to implement value equality at all, override
GetHashCode
and Equals(object)
- creating overloads for == and implementing IEquatable<T>
without doing that could result in very unexpected behaviour
- I would always implement
IEquatable<T>
if you're overriding Equals(object)
and GetHashCode
- I only overload the == operator more rarely
- Implementing equality correctly for unsealed classes is tricky, and can still produce surprising/undesirable results. If you need equality for types in a hierarchy, implement
IEqualityComparer<T>
expressing the comparison you're interested in.
- Equality for mutable types is usually a bad idea, as two objects can be equal and then unequal later... if an object is mutated (in an equality-affecting way) after it's been used as a key in a hash table, you won't be able to find it again.
- Some of the boiler-plate is slightly different for structs... but like Marc, I very rarely write my own structs.
Here's a sample implementation:
using System;
public sealed class Foo : IEquatable<Foo>
{
private readonly string name;
public string Name { get { return name; } }
private readonly int value;
public int Value { get { return value; } }
public Foo(string name, int value)
{
this.name = name;
this.value = value;
}
public override bool Equals(object other)
{
return Equals(other as Foo);
}
public override int GetHashCode()
{
int hash = 17;
hash = hash * 31 + (name == null ? 0 : name.GetHashCode());
hash = hash * 31 + value;
return hash;
}
public bool Equals(Foo other)
{
if ((object) other == null)
{
return false;
}
return name == other.name && value == other.value;
}
public static bool operator ==(Foo left, Foo right)
{
return object.Equals(left, right);
}
public static bool operator !=(Foo left, Foo right)
{
return !(left == right);
}
}
And yes, that's a heck of a lot of boilerplate, very little of which changes between implementations :(
The implementation of ==
is slightly less efficient than it might be, as it will call through to Equals(object)
which needs to do the dynamic type check... but the alternative is even more boiler-plate, like this:
public static bool operator ==(Foo left, Foo right)
{
if ((object) left == (object) right)
{
return true;
}
// "right" being null is covered in left.Equals(right)
if ((object) left == null)
{
return false;
}
return left.Equals(right);
}