public static int GetIdentityHashCode(object obj) { System.Reflection.MethodInfo methodInfo = null; Type type = typeof(object); methodInfo = type.GetMethod("GetHashCode"); return (int) methodInfo.Invoke(obj, null); }
Why can't we call: public static int GetIdentityHashCode(object obj) { return obj.GetHashCode(); } Does using reflection call the framework's GetHashCode method even if the object has overriden it? Can we cache the MethodInfo? public class HashCodeProvider { private static MethodInfo getHashCodeMethodInfo = null; static HashCodeProvider() { Type type = typeof(object); getHashCodeMethodInfo = type.GetMethod("GetHashCode"); } public static int GetIdentityHashCode(object obj) { return (int)getHashCodeMethodInfo.Invoke(obj, null); } }