Skip to content

Instantly share code, notes, and snippets.

@alastairs
Created April 1, 2020 08:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alastairs/bba72ba25e170c5cc3810f44b1a0337f to your computer and use it in GitHub Desktop.
Save alastairs/bba72ba25e170c5cc3810f44b1a0337f to your computer and use it in GitHub Desktop.
Equality implementation in C#
namespace EqualityDemo
{
public class Person : IEquatable<Person>
{
public string GivenName { get; }
public string FamilyName { get; }
public Address Address { get; }
public override bool Equals(object other)
{
return Equals(other as Person);
}
public override int GetHashCode()
{
return HashCode.Combine(GivenName, FamilyName, Address);
}
public bool Equals(Person other)
{
return Equals(this, other);
}
public static bool Equals(Person a, Person b)
{
if (ReferenceEquals(a, b))
{
return true;
}
// You can use a == null || b == null here, *unless* you are overriding the equality operators,
// in which case you'll end up with a StackOverflowException
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a.GivenName == b.GivenName &&
a.FamilyName == b.FamilyName &&
a.Address == b.Address;
}
}
public class Address : IEquatable<Address>
{
public string Line1 { get; }
public string Line2 { get; }
public string City { get; }
public string County { get; }
public PostCode PostCode { get; }
public override bool Equals(object other)
{
return Equals(other as Address);
}
public override int GetHashCode()
{
return HashCode.Combine(Line1, Line2, City, County, PostCode);
}
public bool Equals(Address other)
{
return Equals(this, other);
}
public static bool Equals(Address a, Address b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a.Line1 == b.Line1 &&
a.Line2 == b.Line2 &&
a.City == b.City &&
a.County == b.County &&
a.PostCode == b.PostCode;
}
}
public class PostCode : IEquatable<PostCode>
{
private string _postcode;
public PostCode(string postcode)
{
_postcode = postcode ?? throw new ArgumentNullException(postcode);
}
public override bool Equals(object other)
{
return Equals(other as PostCode);
}
public override int GetHashCode()
{
return _postcode.GetHashCode();
}
public override string ToString()
{
return _postcode;
}
public bool Equals(PostCode other)
{
return Equals(this, other);
}
public static bool Equals(PostCode a, PostCode b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (ReferenceEquals(a, null) || ReferenceEquals(b, null))
{
return false;
}
return a._postcode == b._postcode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment