Implementing custom object for HashSet

798 Views Asked by At

I'm making use of HashSet's for algorithmic purposes, but I am having problems with the implementation of "custom objects". Doing some research it appears one should:

  • Override Equals and GetHashCode (previous question here)
  • Should not generate hashcodes with mutable objects (here yes it's Java, but I figured the implementation was close enough)

My Implementation:

//Simplified version of actual class with key components
class customObject {
    public readonly uint column;
    public readonly char row;

    public customObject(uint column, char row) {
        this.column = column;
        this.row = row;
    }

    public override bool Equals(object obj) {
        return obj is customObj && !ReferenceEquals(this, obj);
    }

    /*where uint column and char row are readonly. HashSet add is not called
    until these variables are set with their lifetime value.*/
    public override int GetHashCode() {
        unchecked {
            var hashCode = row.GetHashCode();
            hashCode = (hashCode * 397) ^ column.GetHashCode();
            return hashCode;
        }
    }
}

//somwhere else
HashSet<customObject> s = new HashSet<customObject>();
for(int i = 0; i < 10; i++) {
    for(char c = 'A'; c < 'J'; c++) {
        s.add(new customObject((uint)i,c));
    }
 }

Unfortunately, I am unable to add my custom object to the HashSet. As I can confirm the count of items in the HashSet is 0 after attempting to add the object. Since there are no items in the set I suspect that I am missing something in the implementation, but have been unable to find a complete answer/tutorial regarding prepping custom objects for use in HashSets.

1

There are 1 best solutions below

2
On
for(char c = 'A'; c < 'A'; c++)

The debugger is your friend; check your loop condition. That loop body will never run. Also, your implementation of GetHashCode would never cause Count == 0 after adding your object with no exception being raised. Lastly, your implementation of Equals is wrong.

It assures that the same object reference will not be considered equal and, if you're going for reference equality, then you don't need to override it in the first place.