Currently I’m using the following class as my key for a Dictionary collection of objects that are unique by ColumnID and a nullable SubGroupID:
public class ColumnDataKey
{
public int ColumnID { get; private set; }
public int? SubGroupID { get; private set; }
// ...
public override int GetHashCode()
{
var hashKey = this.ColumnID + "_" +
(this.SubGroupID.HasValue ? this.SubGroupID.Value.ToString() : "NULL");
return hashKey.GetHashCode();
}
}
I was thinking of somehow combining this to a 64-bit integer but I’m not sure how to deal with null SubGroupIDs. This is as far as I got, but it isn’t valid as SubGroupID can be zero:
var hashKey = (long)this.ColumnID << 32 +
(this.SubGroupID.HasValue ? this.SubGroupID.Value : 0);
return hashKey.GetHashCode();
Any ideas?
Strictly speaking you won’t be able to combine these perfectly because logically
int?has 33 bits of information (32 bits for the integer and a further bit indicating whether the value is present or not). Your non-nullableinthas a further 32 bits of information making 65 bits in total but alongonly has 64 bits.If you can safely restrict the value range of either of the ints to only 31 bits then you’d be able to pack them roughly as you’re already doing. However, you won’t get any advantage over doing it that way – you might as well just calculate the hash code directly like this (with thanks to Resharper’s boilerplate code generation):