tags:

views:

159

answers:

2

Is it possible to compute the hash of a class at runtime in C# (presumably through reflection)? To be clear, I don't want to compute the hashcode of an instance of said class, I want to compute the hash of the class code itself (if a function in the class changes, I'd expect a different hash code to be computed). Ideally this would only be sensitive to changes in the object code (and not just a hash of the string representation of the code itself).

Thanks in advance for your help,

-- Breck

+1  A: 

You don't need to use reflection. You can try System.Type.GetHashCode(). I'm not sure how it works, if not optimal, than you can always use type.FullName.GetHashCode()

Andrew Bezzub
Type.GetHashCode() seems to change its value between recompiles. type.FullName.GetHashCode() wouldnt' change hashes for when a method changes.
Jimmy
System.Type.GetHashCode will work just fine, it will change if a method name changes or a parameter name / type changes, etc., type.FullName.GetHashCode will not work as the type name could stay the same but a method might change.
John JJ Curtis
@Jeff: class Program { static void Main() { Console.Write(typeof(Program).GetHashCode(); } } changes its output between compiles.
Jimmy
@Jimmy You're right, I should have run my test twice with the same exact class, sorry...
John JJ Curtis
+3  A: 

If you have the Type you can use GetMethod to get an instance of MethodInfo, which in turn has a GetMethodBody that returns the IL for said method. You can then hash that.

I am curious. Why do you want to do this in the first place?

Brian Rasmussen
The reason I want to do this is that in my case I have a function, f, of considerable time complexity. The problem is that I'm experimenting with the values f should be returning, so f changes frequently. If a particular version of f, fi, has already run for an input, x, I want to cache the result, fi(x) so that if fi runs again, it can just use the memoized value.
Breck Fresen
Thanks for the explanation.
Brian Rasmussen