The equality pattern I like to see in C# is as follows:
For entity type classes
“Many objects are not fundamentally defined by their attributes, but rather by a thread of continuity and identity.” -Eric Evans
-
-
-
- class Entity : IEquatable<Entity>
- {
- private readonly Int32 _Identifier;
-
- public Entity(Int32 identifier)
- {
- _Identifier = identifier;
- }
-
- public override bool Equals(object obj)
- {
- var result = Equals(obj as Entity);
- return result;
- }
-
- public override int GetHashCode()
- {
- var result = _Identifier.GetHashCode();
- return result;
- }
-
-
- public bool Equals(Entity other)
- {
- if (ReferenceEquals(other, null))
- return false;
-
- var result = _Identifier == other._Identifier;
- return result;
- }
-
-
- public static Boolean operator ==(Entity target, Entity other)
- {
- if (ReferenceEquals(target, other))
- return true;
-
- if (ReferenceEquals(target, null))
- return false;
-
- var result = target.Equals(other);
- return result;
- }
-
- public static Boolean operator !=(Entity target, Entity other)
- {
- var result = !(target == other);
- return result;
- }
-
- }
For value type classes
“Many objects have no conceptual identity. These objects describe characteristics of a thing.” -Eric Evans
-
-
-
- class Value :IEquatable<Value>
- {
- private readonly Int32 _Property1, _Property2;
-
- public Value(Int32 property1, Int32 property2)
- {
- _Property1 = property1;
- _Property2 = property2;
- }
-
- public override bool Equals(object obj)
- {
- var result = Equals(obj as Value);
- return result;
- }
-
- public bool Equals(Value other)
- {
- if (ReferenceEquals(other, null))
- return false;
-
- var result =
- _Property1 == other._Property1 &&
- _Property2 == other._Property2;
-
- return result;
- }
-
- public override int GetHashCode()
- {
- var result =
- _Property1.GetHashCode() ^
- _Property2.GetHashCode();
-
- return result;
- }
-
-
- public static Boolean operator == (Value target, Value other)
- {
- if (ReferenceEquals(target, other))
- return true;
-
- if (ReferenceEquals(target, null))
- return false;
-
- var result = target.Equals(other);
- return result;
- }
-
- public static Boolean operator !=(Value target, Value other)
- {
- var result = !(target == other);
- return result;
- }
- }