RuntimeHelpers::GetHashCode Method (Object)
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures such as a hash table.
Assembly: mscorlib (in mscorlib.dll)
Parameters
- o
- Type: System::Object
An object to retrieve the hash code for.
The RuntimeHelpers::GetHashCode method always calls the Object::GetHashCode method non-virtually, even if the object's type has overridden the Object::GetHashCode method. Therefore, using RuntimeHelpers::GetHashCode differs from calling GetHashCode directly on the object with the Object::GetHashCode method.
The Object::GetHashCode and RuntimeHelpers::GetHashCode methods are used in the following scenarios:
Object::GetHashCode is useful in scenarios where you care about object value. Two strings with identical contents will return the same value for Object::GetHashCode.
RuntimeHelpers::GetHashCode is useful in scenarios where you care about object identity. Two strings with identical contents will return different values for RuntimeHelpers::GetHashCode, because they are different string objects, although their contents are the same.
This method is used by compilers.
String Interning
The common language runtime (CLR) maintains an internal pool of strings and stores literals in the pool. If two strings (for example, str1 and str2) are identical, the CLR will set str1 and str2 to point to the same location on the managed heap to conserve memory. Calling RuntimeHelpers::GetHashCode on these two string objects will produce the same hash code, contrary to the second bulleted item in the previous section.
The CLR adds only literals to the pool. Results of string operations such as concatenation are not added to the pool. Therefore, if str2 was created as the result of a concatenation operation, and str2 is identical to str1, using RuntimeHelpers::GetHashCode on these two string objects will not produce the same hash code.
If you want to add a concatenated string to the pool explicitly, use the String::Intern method.
You can also use the String::IsInterned method to check whether a string has an interned reference.
The following example demonstrates how a compiler might use the RuntimeHelpers::GetHashCode method to generate a hash code.
Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.