Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kenny-evitt/9994dbd9aeccfe312ce6 to your computer and use it in GitHub Desktop.
Save kenny-evitt/9994dbd9aeccfe312ce6 to your computer and use it in GitHub Desktop.
Template for simple equality implementation for C# classes
// Public operators
public static bool operator ==(SomeClass item1, SomeClass item2)
{
if (System.Object.ReferenceEquals(item1, item2))
return true;
if (((object)item1 == null) || ((object)item2 == null))
return false;
if ((item1.SomeSequence == null && item2.SomeSequence != null)
||
(item1.SomeSequence != null && item2.SomeSequence == null))
{
return false;
}
bool areSomeSequenceSequencesEqual = false;
if (item1.SomeSequence == null && item2.SomeSequence == null)
{
areSomeSequenceSequencesEqual = true;
}
else
{
areSomeSequenceSequencesEqual = item1.SomeSequence.SequenceEqual(item2.SomeSequence);
}
return
item1._someField == item2._someField
&& areSomeSequenceSequencesEqual;
}
public static bool operator !=(SomeClass item1, SomeClass item2)
{
return !(item1 == item2);
}
// Public methods
public override bool Equals(object obj)
{
return Equals(obj as SomeClass);
}
public bool Equals(SomeClass other)
{
return this == other;
}
public override int GetHashCode()
{
return
_someField.GetHashCode()
^ ((this.SomeSequence == null) ? 0 : this.SomeSequence.GetHashCode());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment