Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the GetHashCode() method of a string return zero?

Tags:

.net

hashcode

When obtaining the hash code of a string using the GetHashCode() method is there any chance that it can return zero or does the algorithm used guarantee otherwise?

The reason I'm asking is that I have a use case where I need to invent a hash for a null string and I was thinking of using zero rather than hashing some constant string. If I do this how likely am I to get a collision (barring the obvious fact that collisions are always possible)

like image 709
RobV Avatar asked Oct 26 '25 15:10

RobV


1 Answers

There's no way to definitively answer that. The behavior of String.GetHashCode() is documented as being undefined and subject to change between framework versions and to be different between 32bit and 64 bit systems.

If you chose some other value you may be just as likely to have a collision. Zero would be a pretty reasonable default.

The Nullable.GetHashCode() returns 0 if it stores a null value so return a hash code for zero has some precedent.

like image 192
shf301 Avatar answered Oct 29 '25 07:10

shf301