C# : How to write a custom Equality Comparer to be used for a HashSet

I need to write a custom Equality Comparer to be used for a class that I created.

Class that will be used for the HashSet

 ///<summary>Item for HashSet example</summary>
public enum ItemGroup
{
    group1 = 1,
    group2,
    group3,
    group4
}
public class Item
{
    public string Name { get; set; }
    public ItemGroup Group { get; set; }

    public Item(string name, ItemGroup group)
    {
        Name = name;
        Group = group;
    }
}
///<summary>Custom Equality Comparer using the base class EqualityComparer<T></summary>
public class MyItemEqualityComparer : EqualityComparer<Item>
{
    //make this a singleton object
    private static readonly MyItemEqualityComparer _instance = new MyItemEqualityComparer();

    public static MyItemEqualityComparer Instance { get { return _instance; } }

    private MyItemEqualityComparer() { }

    public override bool Equals(Item x, Item y)
    {
        return x.Name.ToUpperInvariant() == y.Name.ToUpperInvariant() && x.Group == y.Group;
    }
    public override int GetHashCode(Item obj)
    {
        return obj.Name.ToUpperInvariant().GetHashCode() ^ obj.Group.GetHashCode();
    }
}

Using

class Program
{
    static void Main(string[] args)
    {
        var items = new HashSet<Item>(MyItemEqualityComparer.Instance);
        items.Add(new Item("Item 1", ItemGroup.group1));
        items.Add(new Item("Item 2", ItemGroup.group2));
        items.Add(new Item("ITEM 3", ItemGroup.group3));
        items.Add(new Item("ITEM 3", ItemGroup.group3));
        items.Add(new Item("Item 3", ItemGroup.group3));

        foreach (Item item in items)
        {
            Console.WriteLine($"Item's name : {item.Name}, Item's Group : {item.Group.ToString()}");

        }
    }
}

Outputs

  • Item’s name : Item 1, Item’s Group : group1
  • Item’s name : Item 2, Item’s Group : group2
  • Item’s name : ITEM 3, Item’s Group : group3