In the implementation of GetHashCode
below, when Collection
is null
or empty will both result in a hash code of 0
.
A colleague suggested return a random hard coded number like 19
to differentiate from a null
collection. Why would I want to do this? Why would I care that a null
or empty collection produces a different hash code?
public class Foo
{
public List<int> Collection { get; set; }
// Other properties omitted.
public int override GetHashCode()
{
var hashCode = 0;
if (this.Collection != null)
{
foreach (var item in this.Collection)
{
var itemHashCode = item == null ? 0 : item.GetHashCode();
hashCode = ((hashCode << 5) + hashCode) ^ itemHashCode;
}
}
return hashCode;
}
}
GetHashCode
in tie first place? What do you want to achieve? – Utmostnull
from an empty collection in a hash code? – Internethrow new NotImplementedException();
– Beaubeauchamp