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?