Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good value for a null safe hashcode function to return when the argument is null? [duplicate]

Tags:

c#

null

hashcode

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?

like image 704
Sidney Avatar asked Dec 30 '25 08:12

Sidney


1 Answers

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.

like image 150
John Somsky Avatar answered Dec 31 '25 22:12

John Somsky