Reputation: 27
Reading HashSet on MSDN, it says with HashSet<T>
, if T implements IEquatable<T>
then the HashSet uses this for IEqualityComparer<T>.Default
.
So, let the class Person:
public class Person : IEquality<Person>
{
private string pName;
public Person(string name){ pName=name; }
public string Name
{
get { return pName; }
set
{
if (pName.Equals(value, StringComparison.InvariantCultureIgnoreCase))
{
return;
}
pName = value;
}
}
public bool Equals(Person other)
{
if(other==null){return false;}
return pName.Equals(other.pName, StringComparison.InvariantCultureIgnoreCase);
}
public override bool Equals(object obj)
{
Person other = obj as Person;
if(other==null){return false;}
return Equals(other);
}
public override int GetHashCode(){return pName.GetHashCode();}
public override string ToString(){return pName;}
}
So, let's define in another class or main function:
HashSet<Person> set = new HashSet<Person>();
set.Add(new Person("Smith"); // return true
Person p = new Person("Smi");
set.Add(p); // return true
p.Name = "Smith"; // no error occurs
And now, you've got 2 Person objects in the HashSet with the same name (so that, there are "Equals").
HashSet let us put duplicate objects.
Upvotes: 1
Views: 1623
Reputation: 564851
HashSet let us put duplicate objects.
It isn't letting you put in duplicate objects. The issue is that you're mutating the object after it's been added.
Mutating objects being used as keys in dictionaries or stored as hashes is always problematic, and something I would recommend avoiding.
Upvotes: 11