1

I am a bit confused about calling HashCode.Combine in a non generic way

HashCode has public void Add<T> (T value);

but not public void Add (object value);

In my case I need to calculate the combined hashcode of an unknown number of objects of unknown types.

Is it OK to do:

object v1 = ...
object v2 = ...
object v3 = ...

var hashCodeStruct = new HashCode();
hashCodeStruct.Add(v1);
hashCodeStruct.Add(v2);
hashCodeStruct.Add(v3);
var hashCode = hashCodeStruct.ToHashCode();

?

kofifus
  • 17,260
  • 17
  • 99
  • 173

1 Answers1

1

Calling Add<object>(x) and Add<SomeOtherType>(x) will produce the same hash code. The only difference is that the former will box x if x is a value type. I'm pretty sure Add is made generic so that boxing does not occur if you pass in a value type. However, this is irrelevant here, because you are dealing with reflected objects (which are possibly boxed before the call to Add).

Here's the reference source of Add:

public void Add<T>(T value)
{
    Add(value?.GetHashCode() ?? 0);
}

...

private void Add(int value)
{

    ...

It just very simply calls the private Add with value's hash code. It is easy to see that the same implementation of GetHashCode will be called no matter what T is, as long as value is the same object, because runtime polymorphism.

Sweeper
  • 213,210
  • 22
  • 193
  • 313