runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Lambdas with same signature always have same hash codes

Open mcdirmid opened this issue 11 years ago • 10 comments

In debugging my last issue (Expression.Invoke not being thread safe), I ran into a problem with code execution in being tell my lambdas apart since they had the same signature; consider:

capture

Since the hashcode of f and g is the same, the only way I can tell them apart in the debugger is by (a) executing them, (b) comparing them via equality, or (c) using the IDE's assign ID function. I realize unequal objects can have the same hash code by accident, but I think it is not very useful if unequal objects always have the same hash code, if only for debugging purposes.

In normal Windows, a work around is probably to use the hashcode of Method (e.g. f.Method.GetHashCode()), which seems to return a more diverse result. However, in universal Windows, that member isn't available. We could also use the string, but that isn't useful when the lambda is compiled via the DLR.

mcdirmid avatar Oct 28 '15 04:10 mcdirmid

Seems there's some subtlety here for delegate types wrt JIT behavior. See https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Delegate.cs#L177-L190 for some comments. Someone from CoreCLR can chime in.

bartdesmet avatar Oct 28 '15 06:10 bartdesmet

That isn't very satisfying. At the very least, we should have some API that can be used to help uniquely identify the lambda during debugging. That HashCode is overloaded for multiple uses is unfortunate, and ToString is essentially useless for lambdas (they just regurgitate type signatures and nothing else useful). Adding something like Method to UWP might help.

mcdirmid avatar Oct 28 '15 06:10 mcdirmid

For some uses you could use System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode() which obtains the hashcode it would have if there was no override and hence corresponds to reference identity. If though you wanted Func h = () => 1; to mean that h had the same hashcode as f, then this is even worse than the override.

JonHanna avatar Oct 28 '15 09:10 JonHanna

Great tip, thanks! I just want to know when two lambdas aren't the same in my LOG statements.

mcdirmid avatar Oct 28 '15 09:10 mcdirmid

You can use https://www.nuget.org/packages/AisA/ for the same thing if you might need to worry about the compact framework where RuntimeHelpers isn't available, but that isn't a concern with .NET Core. (I must check that it does work with .NET Core too though). Again though, it helps some cases but it's worse than the heavy collisions in others.

JonHanna avatar Oct 28 '15 10:10 JonHanna

I've checked, the API exists in UWP, which is all I need.

mcdirmid avatar Oct 28 '15 10:10 mcdirmid

Is there anything still needed here?

We've a way of hashing on signature (the default), we've a way of hashing on reference identity (RuntimeHelpers), and I'm not sure anything else (such as considering two completely equivalent delegates to be the same) is viable.

JonHanna avatar Oct 30 '15 10:10 JonHanna

What about just better documentation? It is really hard to find any of this stuff out as these design decisions are fairly opaque from a user perspective. The documentation for Delegate.GetHashCode() right now simply states "returns the hash code for the delegate" (note, docs shouldn't just regurgitate what you can read in the signature!). I see the MSDN docs are a bit more detailed:

The return value of this method must not be persisted for two reasons. First, the hash function of a class might be altered to generate a better distribution, rendering any values from the old hash function useless. Second, the default implementation of this class does not guarantee that the same value will be returned by different instances.

But that is actually the opposite of what is really going on (maybe inherited from object?); talk about misleading! It really should read something like:

As an implementation limitation, delegates that return and take the same types will always have the same hash code. Use RuntimeHelpers instead if a more precise hash code is needed for debugging or hashing purposes.

Long term, this is ugly and should be fixed someday even if it can be worked around.

mcdirmid avatar Oct 30 '15 11:10 mcdirmid

I disagree. As soon as it's documented, it becomes a contract. The current documentation is correct: the hash code implementation can change tomorrow if needed, you shouldn't rely on it.

Yes, the generated hash code is not optimal and probably should be better, I sympathize with that. Still, it respects its contract (tomorrow, every object in the runtime could return the exact same hash code and that would still be valid, only very bad for performance).

As to why the hash code is the same for each delegate type, please see the commented code in Delegate.cs:182 which explains it.

If you want to check for reference equality at runtime, ReferenceEquals is here. For debugging purposes, there's Make object ID in VS which was made to solve specifically this kind of problems. You can also show the address of any managed object in the watch window using &, if you prefer.

At runtime, if you really need to, for logging purposes, there are several ways to get the address of an object, although they're not very safe and the address can change if you don't keep the object pinned. You can also use ObjectIDGenerator or make your own (keep a set with a reference equality comparer, generate a new ID if your object isn't in the set) which is IMO the best solution for your problem.

MrJul avatar Oct 30 '15 13:10 MrJul

Make Object Id doesn't work in Console.WriteLine statements (or any programmatic tracing abstraction, maybe it should?); object.referenceequals requires a point of comparison. Neither would help me debug the issue I was having before. I've also used object ID generators when really desperate, but I usually just use an ID off hash code converted to alpha string first since (a) it is usually unique if not computed and (b) it is always there. This is the first time I've ever noticed a non-value object with such an imprecise hash code, so maybe I should use object ID generators more often because...delegates prove that hash codes can be bad for debugging?

Anyways, my problem is fixed with a way to get real hash codes via RuntimeHelper. The general inadequacy of .net documentation with its inability to communicate important nuances in API behavior because they would be "specifying a contract" is another issue that won't be solved here. The behavior and work arounds should be documented somewhere at least, maybe on stackoverflow or maybe just by virtue of this github issue being indexed by Google.

mcdirmid avatar Oct 30 '15 14:10 mcdirmid