Code example for overriding the GetHashCode method in C#

Below programs illustrate the use of
Single.GetHashCode()
Method:
Example 1:
Output:
Example 2:
Output:
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.single.gethashcode?view=netstandard-2.1
Solution:
Make sure you implement the Equals method according to the MS guide. GetHashCode methods.


Solution 1:

 _testDict.Add(new KeyModifierSet(Key.A), () => Debug.WriteLine("nothing"));
 if (!_testDict.ContainsKey(new KeyModifierSet(Key.A))) throw new Exception("Not done yet, help :-)");

It seems that you’re trying to compare your _testDict Dictionary object for equality using customized versions of the Object.Equals and Object.GetHashCode methods. However, it’s worth noting that in order to achieve this, you’ll need to develop your own custom collection type that implements those methods.


Solution 2:


Here’s the solution to my own question, which was a bit complex.

public class KeyModifierSet
{
    internal readonly HashSet Keys = new HashSet();
    internal readonly HashSet MKeys = new HashSet();
    public override int GetHashCode()
    {
        int hash = Keys.Count + MKeys.Count;
        foreach (var t in Keys)
        {
            hash *= 17;
            hash = hash + t.GetHashCode();
        }
        foreach (var t in MKeys)
        {
            hash *= 19;
            hash = hash + t.GetHashCode();
        }
        return hash;
    }
    public override bool Equals(object obj)
    {
        return Equals(obj as KeyModifierSet);
    }
    public bool Equals(KeyModifierSet other)
    {
        // Check for null
        if (ReferenceEquals(other, null))
            return false;
        // Check for same reference
        if (ReferenceEquals(this, other))
            return true;
        // Check for same Id and same Values
        return Keys.SetEquals(other.Keys) && MKeys.SetEquals(other.MKeys);
    }
    public KeyModifierSet(ModifierKeys mKey)
    {
        MKeys.Add(mKey);
    }
    public KeyModifierSet(Key key)
    {
        Keys.Add(key);
    }
    public KeyModifierSet(Key key, ModifierKeys mKey)
    {
        Keys.Add(key);
        MKeys.Add(mKey);
    }
    public KeyModifierSet Add(Key key)
    {
        Keys.Add(key);
        return this;
    }
    public KeyModifierSet Add(ModifierKeys key)
    {
        MKeys.Add(key);
        return this;
    }
}

Frequently Asked Questions

Posted in Uncategorized