Can anyone tell me how is ObjectIDGenerator better (worse?) then using HashSet when traversing an hierarchy of objects (that might be recurvise/circular), and not wanting to traverse the same object twice?
Can anyone tell me how is ObjectIDGenerator better (worse?) then using HashSet when traversing
Share
The basic difference is in how each one does equality.
ObjectIdGenerator looks at referential identity. When checking to see if an object is present already it will simply do an == call on the two object instances. This will boil down to a reference comparison because the objects are statically type to be object at this point. This is fine unless your object explicitly uses .Equals() for equality. If two objects are equal via .Equals() but different references, ObjectIDGenerator will consider them different objects. Likely not what you want.
HashSet on the other hand allows you to customize the way in which you compare objects via the IEqualityComparer<T> parameter. If none is specified it will use EqualityComparer<T>.Default which will use value equality. This method will call into .Equals() and depend on it to determine if two objects are equal. In the case where you didn’t define a .Equals() method for your types it will default back to reference equality which is almost certainly what you want.
In short, go with HashSet 🙂
Sample Code showing the difference: