Search code examples
c#arraysiequalitycomparer

Prevent adding two items with the same byte[] key in from being added to a KeyedCollection<byte[], MyObject>


Code:

public class Coll : KeyedCollection<byte[], MyObject>
{
    protected override byte[] GetKeyForItem(MyObject item) => item.Key;
    
}

public class EquComparer : IEqualityComparer<byte[]>
{
    public bool Equals(byte[]? x, byte[]? y)
    {
        if (x is null && y is null) return true;
        if (x is null) return false;
        if (y is null) return false;
        return x.SequenceEqual(y);
    }

    public int GetHashCode([DisallowNull] byte[] obj)
    {
        int result = Int32.MinValue;
        foreach (var b in obj)
        {
            result += b;
        }

        return result;
    }
}

My key is byte[]. I want to set the default equality comparer to compare keys with to something using byte[]::SequenceEqual() to keep two items with the same keys from being added.

Is there a way to do this?

Edit: As other have pointed out I could use the constructor to specify a non default equality comparer. I am certain it will be forgotten at some point giving rise to a bug that will be difficult to find. That is why I want to add some code to the class that makes my custom equality comparer the default for that class.


Solution

  • The KeyedCollection<TKey,TItem> class has a constructor that accepts an IEqualityComparer<TKey>. You could invoke this constructor when instantiating the derived class:

    public class Coll : KeyedCollection<byte[], MyObject>
    {
        public Coll() : base(new EquComparer()) { }
    
        protected override byte[] GetKeyForItem(MyObject item) => item.Key;
    }