Masoud
Masoud

Reputation: 1405

Different Hash code for same arrays in C#

This is pseudo code

sbyte[] array1 = new sbyte[100]; 
array1.setValues(); 
sbyte[] array2 = (sbyte[])array1.Clone();

But array1.getHashCode() is not equal with array2.getHashCode();

What should I do to get same hash code for array1 and array2?

P.S: Dictionary isn't useful. Because I wanted to add these arrays to a hashtable. And after each adding I need to check for a possible same content array added before.

P.S2: It seems I should clarify my problem. At first I posted the complete question at Using Hash in C# and when it was solved this question was raised.

Upvotes: 4

Views: 3346

Answers (2)

CARLOS LOTH
CARLOS LOTH

Reputation: 4745

There is no way to override the GetHashCode method from the array class. But you can wrap you array inside another class and them use some of its items to specify its hash key.

public class WrappedArray
{
  sbyte[] _inner = new sbyte[10]

  //...

  override public int GetHashCode()
  {
    return _inner[0] ^ _inner[1] ^ _inner[2];
  }
}

It is just an idea. The hash codes don't need to be unique for each object, because hash structures are designed to deal with collisions.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1062905

That isn't the same array - it is a different array with the same contents.

An array GetHashCode() doesnt hash the contents. That hash is simple a hash of the reference.

You could write a custom IEqualityComparer<sbyte[]> if needed for a dictionary etc.

Upvotes: 13

Related Questions