There is no (at least not completely hacked) way to hash an anonymous function / delegate. Even if the implementation of the function is the same, it can be a closure, so the result of the check may differ depending 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; } }
Thus, the only way to verify that the validation function is unique would be for the caller to determine the uniqueness of the validation implementation and provide the caller with this information for you. You will need to switch to using some kind of validator interface, something like this:
// // 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 as follows:
GetContent(new Validator("foo"), new ValidatorEqualityComparer());
So, the most important part that should be noted here is that when implementing ValidatorEqualityComparer.GetHashCode() you use a validator object hash (based on the value of the object) . Only this guarantees the true uniqueness of the verification logic.
source share