I need to implement the IEqualityComparer<Delegate>
interface to define an implementation of GetHashCode()
for delegates. This is needed because I wish to have a dictionary with delegates as keys, and the default implementation of GetHashCode() for delegates is simply ->
public override int GetHashCode()
{
return base.GetType().GetHashCode();
}
As noted here - Why do 2 delegate instances return the same hashcode? - the above, default implementation will make using delegates in a dictionary as slow as a list (O(n)
for lookups).
So I am considering my own implementation which uses System.Reflection.MethodInfo like so ->
public int GetHashCode(Delegate? obj)
{
if (obj == null)
return 0;
else
return obj.Method.GetHashCode();
}
But given that MethodInfo's GetHashode() method is contained in the system.reflection namespace, will the above implementation be very slow? I know that reflection can be costly, and since the GetHashCode() method will be used by the dictionary it is important that invocations are not slow.