[Mono-list] Changing GetHashCode return value

Serge serge@wildwestsoftware.com
Sat, 9 Mar 2002 16:19:15 +0200


The code below demonstrates how to "manually" change the value returned by
the default implementation of Object.GetHashCode() under .NET runtime.
This trick is absolutely useless in practice, but still looks funny, so here
it is.
Also, may be useful to understand what's going on behind the scenes.

----------
// csc /unsafe change_hash.cs

using System;
using System.Runtime.InteropServices;

class HashChange {
   unsafe public static void Main (string [] args) {
     object o = new object();

     GCHandle gch = GCHandle.Alloc(o);
     int* p_handle = (int*) (IntPtr) gch;
     int* p_obj = *(int**)p_handle;
     int* p_hash = p_obj - 1;
     *p_hash = 0x123;
     gch.Free();

     Console.WriteLine("0x{0}", o.GetHashCode().ToString("X"));
   }
}
----------

It will print 0x123 or whatever value you will write to *p_hash.
Some values will crash the runtime though ;-)


Sergey