I want to make every instance of a class X
having a unique ID.
I'm doing this using a incremented number:
class X {
private int id;
private static int instanceCounter = 0;
public X() {
id = Interlocked.Increment(ref instanceCounter);
}
//...
}
The objects are also used as keys in dictionaries, so I thought I could return id
from GetHashCode()
.
public override int GetHashCode() {
return id;
}
I'm aware of Eric Lippert's post, but it always talks about calculating hashs from multiple data stored in the object.
In my case, the only 'unique' data is id
.
So the question is:
Is there something I haven't thought about with this approach?
If you want each object to be distinct (so not equal to any other object) then just don't override Equals
and GetHashCode
at all. The default is to give a "probably unique" hash code, which is all you need to narrow the choices down - and Equals
will use reference identity, which is what you want. There's no need to have a separate id
field, just for equality.
If you do need the id
field for other reasons, you can certainly return it from GetHashCode
- I would suggest making it a readonly field to make your intentions clear though.
Note that hash codes should never be used as a definite positive equality check anyway - they're only used to rule out instances which are definitely not equal to each other.
See more on this question at Stackoverflow