I'm currently working on a .net 5.0 application.
I need to implement an IEqualityComparer.
What is the correct way, to implement this interface and prevent NullRefrence Exceptions?
- My class to compare looks like this:
public class Fruit
{
public int Id { get; set; }
public string Name { get; set; }
}
- My IEqualityComparer should compare the Ids and looks like this
public class FruitComparer : IEqualityComparer<Fruit>
{
public bool Equals(Fruit x, Fruit y)
{
return x?.Id == y?.Id;
}
public int GetHashCode(Fruit obj)
{
return obj.Id;
}
}
The code works fine - but I wonder if that's the way to implement this interface?
What's the correct solution to implement an IEqualityComparer?
That looks largely fine. You're open to a
NullReferenceExceptionif someone callsGetHashCode(null), although this is unlikely to happen. You should also make a habit of callingGetHashCodeon the members of your type, although for anintthat doesn't make any difference.A good solution is:
Expanding this to multiple properties is slightly more boilerplate-y, something such as: