
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Creating a Hash Code for a Data Type
|
601
public int ConcatStringGetHashCode(int[] someIntArray)
{
int hashCode = 0;
StringBuilder hashString = new StringBuilder( );
if (someIntArray != null)
{
foreach (int i in someIntArray)
{
hashString.Append(i.ToString( ) + "^");
}
}
hashCode = hashString.GetHashCode( );
return (hashCode);
}
The following using directives must be added to any file containing this code:
using System;
using System.Text;
using System.Security.Cryptography;
Discussion
The GetHashCode method is called when you are using an instance of this class as the
key in a
Hashtable or Dictionary<T,U> object. Whenever your object is added to a
Hashtable or Dictionary<T,U> as a key, its GetHashCode method is. A hash code is also
obtained from your object when a search is performed for it in the
Hashtable or
Dictionary<T,U>.
The following class implements the
SimpleHash algorithm for the overloaded
GetHashCode method:
public class SimpleClass
{
private int x = 0;
private int y = 0;
public override int GetHashCode( )
{
return(SimpleHash(x, y));
}
private static int SimpleHash(params int[] values)
{
int hashCode = 0;
if (values != null)
{
foreach (int val in values)
{
hashCode ^= val;
}
}