How can I get a hash of a delegate function in C#. I want to be able to tell if different delegates are being sent into my function. My code looks something like this:
public string GetContent(Func<string, bool> isValid)
{
// Do some work
SomeFunctionToHashAFunction(isValid)
}
I would use .GetHashCode() but the .NET framework doesn’t guarantee that these will be unique.
EDIT
I have some cached content that I’m validating, but I only want to validate it once. However, if the validation function changes, then I’ll need to re-validate the cached content. I’m not sure if the ObjectIdGenerator will work in this instance since I need to identify if two anonymous functions have the same implementation.
There is no (at least non completely hacky) way to hash anonymous function/delegate. Even if function implementation is the same, it might be a closure – so validation outcome might be different based on the context state. Consider this example:
So the only way be sure of whether the validation function is unique would be to have caller define uniqueness of validation implementation and have the caller pass that information to you. You would have to switch to using some kind of validator interface, something along these lines:
Then you can call your method like this:
So the most important part to note here, is that when implementing
ValidatorEqualityComparer.GetHashCode()you use validator object state (object value based) hashing. Only this will ensure true uniqueness of validation logic.