3

So I've got an object with a large number of properties, and I need to compare them, ergo, I have to overwrite GetHashCode. This is a headache because any of the properties can be null, so I have several repeated lines

int hashcode = 0;
if (!String.IsNullOrEmpty(Property1)) hashcode ^= Property1.GetHashCode();
if (!String.IsNullOrEmpty(Property2)) hashcode ^= Property2.GetHashCode();
if (!String.IsNullOrEmpty(Property3)) hashcode ^= Property3.GetHashCode();
if (!String.IsNullOrEmpty(Property4)) hashcode ^= Property4.GetHashCode();
....
....
return hashcode * 11; // Use prime multiplication to help evenly distribute hashes

The ammount of repeated "IsNullOrEmpty" makes me unreasonably angsty for some reason, and I don't like it in my code. Even more so, most, but not all properties are strings, so some of them are just "if (obj == null)" which doesn't even line up right. I am not impressed by this solution. In an order to rectify this I'm trying to come up with an extension function, it would look something like this

public static int NullSafeHashCode<T>(this T Hashable)
{
    if(Hashable == null) {return **I have no idea what to put here**;}
    else return Hashable.GetHashCode();
}

I understand that hash codes need only be deterministically created (ergo, no basing it off of a timestamp) such that equal values have equal hashcodes. I'm pretty sure that (null as Foo) == null and (null as Bar) == null evaluates to true, so returning the same hashcode on null objects of disparate types should be reasonable. I understand that where hashcodes are used, if two hashcodes are the same then .Equals is used to verify if they are in fact equal, so collisions aren't an issue. I just don't know what a good, meaningful syntactic value would be for null.

TL; DR?

Look at the second code block. What's a good return value when you're trying to define a HashCode for null?

Sidney
  • 624
  • 7
  • 20
  • 5
    Traditionally you'd use `0`. http://stackoverflow.com/questions/10723458/should-the-hash-code-of-null-always-be-zero-in-net – Asken Apr 22 '16 at 05:27
  • @Asken Thank you! I knew someone had to have asked something similar, my google-fu just wasn't strong enough. Marking as related. =) – Sidney Apr 22 '16 at 05:30

1 Answers1

3

Since a bit-wise or with 0 leave the original value unchanged, I'd suggest returning 0. That will make null values basically be a no-op.

John Somsky
  • 125
  • 11