4

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.

1
  • Hashes are never guaranteed to be unique, by definition. In fact the guarantee is that two objects that return true in Equals return the same hash code (not the other way around). That's why GetHashCode should be used only for lookups and Equals should be used then for the final comparison to verify that two objects really match. Mar 18, 2011 at 19:21

5 Answers 5

5

By definition, a hash is not guaranteed to be unique, so hashing is not what you want.

Instead, you want to determine whether the instance of the delegate has been "seen" before. To do this, you could use ObjectIdGenerator:

private static readonly ObjectIdGenerator oidg = new ObjectIdGenerator();

public string GetContent(Func<string, bool> isValid)
{
    bool firstTime;

    oidg.GetId(isValid, out firstTime);

    if (!firstTime)
    {
        ...
    }
}

However, even with this technique there are some pitfalls to be aware of:

  • ObjectIdGenerator stores a reference to each object you pass to it
  • Delegates to the same function are distinct objects, and would therefore return different IDs

Perhaps if you explain what it is you're trying to achieve, there may be a much better way to go about it.

EDIT: Given your updated requirements, I would just define the validation delegate as a property. If the property changes, you know you need to re-validate. GetContent() would therefore not need any parameters:

public Func<string, bool> IsValidHandler
{
    get { return this.isValidHandler; }
    set 
    {
        this.isValidHandler = value;
        this.requiresValidation = true;
    }
}

public string GetContent()
{
    if (this.requiresValidation && this.isValidHandler != null)
    {
        // do validation

        this.requiresValidation = false;
    }

    // return content
}

You might even simplify further and do the validation when the IsValidHandler property is set (not in the GetContent method).

1
  • +1 Very nice solution, Kent! I didn't even know about ObjectIdGenerator before - this will solve a couple of my problems too! I wish I could give you +2 :)
    – Andrey
    Mar 18, 2011 at 19:25
2

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:

public class Validator
{
    public string SomeState { get; set; }

    public Validator(string someState)
    {
        SomeState = someState;
    }

    public bool IsValid(string input)
    {
        return input == SomeState;
    }
}

// assume your 'input' being validated is "foo"
GetContent((new Validator("foo")).IsValid); // IsValid returns true
GetContent((new Validator("bar")).IsValid); // IsValid returns false

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:

//
// Your code
//

public string GetContent(IValidator validator, 
    IEqualityComparer<IValidator> comparer)
{
    // for tracking used validators, use instance 
    // of 'new HashSet<IValidator>(comparer)'
    // this will give you a hashset of unique validators
}

public interface IValidator
{
    bool IsValid(string input);
}

//
// Your callers code
//

public class Validator : IValidator
{
    // same as Validator class code above
}

public class ValidatorEqualityComparer : IEqualityComparer<Validator>
{
    public bool Equals(Validator v1, Validator v2)
    {
        return GetHashCode(v1) == GetHashCode(v2);
    }

    public int GetHashCode(Validator v)
    {
        int hCode = GetMyStringHash(v.GetType().GUID.ToString() + v.SomeState);
        // as for GetMyStringHash() implementation for this example, 
        // you can use some simple string hashing: 
        // http://www.techlicity.com/blog/dotnet-hash-algorithms.html
        return hCode;
    }
}

Then you can call your method like this:

GetContent(new Validator("foo"), new ValidatorEqualityComparer());

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.

0
2

Hashes are not intended to be unique. In terms of equality, the only thing you can use them for is to determine whether two objects are not the same. As such, they can be used as a quick first test; if the hashes are different, there is no use to do any further comparisons; the two objects are not the same. If the hashes do match, the objects may be the same, but they may also not be, so you need to perform some deeper analysis in order to determine equality.

1

Why not just use HashSet to store delegates? Then you can just use .Contains(isValid) to check if the delegate has been given already.

In other words, someone already solved this problem. No reason for you to also solve it.

-1

GetHashCode WILL be unique between different object to a factor of 2^122, that seems pretty safe.

Otherwise, create a class, add a func property, and a bool that is, HasBeenSeen.

Should get the job done.

7
  • 2
    Some interesting reading for you: Socks, birthdays and hash collisions. Quote: "Anyway, you end up with a 1% chance of a collision after about 9300 tries, and a 50% chance after only 77000 tries." Mar 18, 2011 at 19:23
  • haha, nice. I had never seen that before, but thats a really good read. I push to have GUIDs renamed to GNUIDs. not so catchy. Mar 18, 2011 at 19:27
  • -1 for “pretty safe” — you can't accept “pretty safe” as a principle if you are serious about software engineering. Mar 18, 2011 at 19:28
  • For collisions, I disagree, if the pretty safe solution is 30 minutes, and the 99% safe solution is 3 days, I take the economic solution of 30 minutes, period. If this was security principles I would agree fully, but if you are serious about engineering software you should be serious about not wasting your employers time and money over a 1 off in a million for something not absolutely critical. Mar 18, 2011 at 19:31
  • No. The OP wants to check if he saw or didn't see a delegate before and he apparently can't accept that GetHashCode isn't unique. Hence your “pretty safe” reasoning is wrong. Btw. I am the employer, so I can freely decide what's a waste and what isn't ;-) Mar 18, 2011 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.