lundi 22 mars 2021

Can MethodInfo safely be used for dictionary keys?

I'm trying to use MethodInfo instances as dictionary keys but I am not able to verify that this is well supported by the .net runtime.

To be more precise, given two RuntimeMethodInfo instances m1 & m2 that were obtained from the .net reflection API and are representing the same method. Does the .net runtime always guarantees m1.GetHashCode() == m2.GetHashCode() and m1.Equals(m2) ?

I could find the same question on stackoverflow : Can MethodInfo be used as Dictionary key?

The answer claims that, yes, MethodInfo can be used for dictionary keys. However I was unable to verify this claim.

Looking at the source code of RuntimeMethodInfo, it appears that the implementation of GetHashCode() simply calls the default implementation of RuntimeHelpers.GetHashCode() (when the method is not generic).

If my understanding is correct RuntimeHelpers.GetHashCode(), is only guaranteed to return identical hash codes when objects references are the same.

If my assumption is correct, this would mean that MethodInfo cannot safely be used as a dictionary key unless the reflection API is always guaranteed to return the same MethodInfo instance for the same given method. Is this actually the case ?

Does anybody have more information on this subject ? Thank you !





Aucun commentaire:

Enregistrer un commentaire