I have someone using Type.GetHashCode as if it were a primary key. I think this is a horrible idea but I wanted to know if there was some sort of documented special case that says no two types would have the same hash code.
相关问题
- Generic Generics in Managed C++
- How to Debug/Register a Permanent WMI Event Which
- 'System.Threading.ThreadAbortException' in
- Bulk update SQL Server C#
- Should I use static function in c# where many call
The goal of producing a hash code for an object is to be as unique as possible given the type of data to avoid collisions in the table. But, it's absolutely not guaranteed. Many hash table implementations chain (an array list) off of each hash code bucket to deal with collisions.
It's not guaranteed to be unique.
If your assemblies are strongly named you could use the fully qualified type name as a unique key to identify a
Type
.There are no guarantees around GetHashCode except that it will likely be randomly distributed, not unique. Documentation specifically mentions that:
Random distribution is encouraged to avoid hash collisions (slow Dictionaries):
It is also a very bad idea to persist results of GetHashCode and base any decisions on this persisted value. The same object may return different hash code on a next application execution:
CLR itself changed GetHashCode implementation for a String between .NET 1 and .NET 2 and uses different hash algorithm for 32 and 64 bit versions.
From Guidelines and rules for GetHashCode:
You should be looking at cryptographic hashes if you want almost unique hashcode based on the object value.