String.GetHashCode Method (System) (2024)

Source:
String.Comparison.cs
Source:
String.Comparison.cs
Source:
String.Comparison.cs

Returns the hash code for this string.

public: override int GetHashCode();
public override int GetHashCode ();
override this.GetHashCode : unit -> int
Public Overrides Function GetHashCode () As Integer

Returns

Int32

A 32-bit signed integer hash code.

Examples

The following example demonstrates the GetHashCode method using various input strings.

using namespace System;void DisplayHashCode( String^ Operand ){ int HashCode = Operand->GetHashCode(); Console::WriteLine( "The hash code for \"{0}\" is: 0x{1:X8}, {1}", Operand, HashCode );}int main(){ DisplayHashCode( "" ); DisplayHashCode( "a" ); DisplayHashCode( "ab" ); DisplayHashCode( "abc" ); DisplayHashCode( "abd" ); DisplayHashCode( "abe" ); DisplayHashCode( "abcdef" ); DisplayHashCode( "abcdeg" ); DisplayHashCode( "abcdeh" ); DisplayHashCode( "abcdei" ); DisplayHashCode( "Abcdeg" ); DisplayHashCode( "Abcdeh" ); DisplayHashCode( "Abcdei" );}/*This example displays output like the following: The hash code for "" is: 0x2D2816FE, 757602046 The hash code for "a" is: 0xCDCAB7BF, -842352705 The hash code for "ab" is: 0xCDE8B7BF, -840386625 The hash code for "abc" is: 0x2001D81A, 536991770 The hash code for "abd" is: 0xC2A94CB5, -1029092171 The hash code for "abe" is: 0x6550C150, 1699791184 The hash code for "abcdef" is: 0x1762906D, 392335469 The hash code for "abcdeg" is: 0x1763906D, 392401005 The hash code for "abcdeh" is: 0x175C906D, 391942253 The hash code for "abcdei" is: 0x175D906D, 392007789 The hash code for "Abcdeg" is: 0x1763954D, 392402253 The hash code for "Abcdeh" is: 0x175C954D, 391943501 The hash code for "Abcdei" is: 0x175D954D, 392009037*/
using System;class GetHashCode { public static void Main() { DisplayHashCode( "" ); DisplayHashCode( "a" ); DisplayHashCode( "ab" ); DisplayHashCode( "abc" ); DisplayHashCode( "abd" ); DisplayHashCode( "abe" ); DisplayHashCode( "abcdef" ); DisplayHashCode( "abcdeg" ); DisplayHashCode( "abcdeh" ); DisplayHashCode( "abcdei" ); DisplayHashCode( "Abcdeg" ); DisplayHashCode( "Abcdeh" ); DisplayHashCode( "Abcdei" ); } static void DisplayHashCode( String Operand ) { int HashCode = Operand.GetHashCode( ); Console.WriteLine("The hash code for \"{0}\" is: 0x{1:X8}, {1}", Operand, HashCode ); }}/* This example displays output like the following: The hash code for "" is: 0x2D2816FE, 757602046 The hash code for "a" is: 0xCDCAB7BF, -842352705 The hash code for "ab" is: 0xCDE8B7BF, -840386625 The hash code for "abc" is: 0x2001D81A, 536991770 The hash code for "abd" is: 0xC2A94CB5, -1029092171 The hash code for "abe" is: 0x6550C150, 1699791184 The hash code for "abcdef" is: 0x1762906D, 392335469 The hash code for "abcdeg" is: 0x1763906D, 392401005 The hash code for "abcdeh" is: 0x175C906D, 391942253 The hash code for "abcdei" is: 0x175D906D, 392007789 The hash code for "Abcdeg" is: 0x1763954D, 392402253 The hash code for "Abcdeh" is: 0x175C954D, 391943501 The hash code for "Abcdei" is: 0x175D954D, 392009037*/
let displayHashCode operand = let hashCode = operand.GetHashCode() printfn $"The hash code for \"%s{operand}\" is: 0x{1:X8}, {hashCode}"displayHashCode ""displayHashCode "a"displayHashCode "ab"displayHashCode "abc"displayHashCode "abd"displayHashCode "abe"displayHashCode "abcdef"displayHashCode "abcdeg"displayHashCode "abcdeh"displayHashCode "abcdei"displayHashCode "Abcdeg"displayHashCode "Abcdeh"displayHashCode "Abcdei"(* This example displays output like the following: The hash code for "" is: 0x2D2816FE, 757602046 The hash code for "a" is: 0xCDCAB7BF, -842352705 The hash code for "ab" is: 0xCDE8B7BF, -840386625 The hash code for "abc" is: 0x2001D81A, 536991770 The hash code for "abd" is: 0xC2A94CB5, -1029092171 The hash code for "abe" is: 0x6550C150, 1699791184 The hash code for "abcdef" is: 0x1762906D, 392335469 The hash code for "abcdeg" is: 0x1763906D, 392401005 The hash code for "abcdeh" is: 0x175C906D, 391942253 The hash code for "abcdei" is: 0x175D906D, 392007789 The hash code for "Abcdeg" is: 0x1763954D, 392402253 The hash code for "Abcdeh" is: 0x175C954D, 391943501 The hash code for "Abcdei" is: 0x175D954D, 392009037*)
Module GetHashCode Sub Main() DisplayHashCode("") DisplayHashCode("a") DisplayHashCode("ab") DisplayHashCode("abc") DisplayHashCode("abd") DisplayHashCode("abe") DisplayHashCode("abcdef") DisplayHashCode("abcdeg") DisplayHashCode("abcdeh") DisplayHashCode("abcdei") DisplayHashCode("Abcdeg") DisplayHashCode("Abcdeh") DisplayHashCode("Abcdei") End Sub Sub DisplayHashCode(Operand As String) Dim HashCode As Integer = Operand.GetHashCode() Console.WriteLine("The hash code for ""{0}"" is: 0x{1:X8}, {1}", Operand, HashCode) End Sub End Module ' This example displays output like the following:' The hash code for "" is: 0x2D2816FE, 757602046' The hash code for "a" is: 0xCDCAB7BF, -842352705' The hash code for "ab" is: 0xCDE8B7BF, -840386625' The hash code for "abc" is: 0x2001D81A, 536991770' The hash code for "abd" is: 0xC2A94CB5, -1029092171' The hash code for "abe" is: 0x6550C150, 1699791184' The hash code for "abcdef" is: 0x1762906D, 392335469' The hash code for "abcdeg" is: 0x1763906D, 392401005' The hash code for "abcdeh" is: 0x175C906D, 391942253' The hash code for "abcdei" is: 0x175D906D, 392007789' The hash code for "Abcdeg" is: 0x1763954D, 392402253' The hash code for "Abcdeh" is: 0x175C954D, 391943501' The hash code for "Abcdei" is: 0x175D954D, 392009037

Remarks

The behavior of GetHashCode is dependent on its implementation, which might change from one version of the common language runtime to another. A reason why this might happen is to improve the performance of GetHashCode.

Important

If two string objects are equal, the GetHashCode method returns identical values. However, there is not a unique hash code value for each unique string value. Different strings can return the same hash code.

The hash code itself is not guaranteed to be stable. Hash codes for identical strings can differ across .NET implementations, across .NET versions, and across .NET platforms (such as 32-bit and 64-bit) for a single version of .NET. In some cases, they can even differ by application domain. This implies that two subsequent runs of the same program may return different hash codes.

As a result, hash codes should never be used outside of the application domain in which they were created, they should never be used as key fields in a collection, and they should never be persisted.

Finally, don't use the hash code instead of a value returned by a cryptographic hashing function if you need a cryptographically strong hash. For cryptographic hashes, use a class derived from the System.Security.Cryptography.HashAlgorithm or System.Security.Cryptography.KeyedHashAlgorithm class.

For more information about hash codes, see Object.GetHashCode.

In .NET Framework desktop apps, you can use the <UseRandomizedStringHashAlgorithm> element to generate unique hash codes on a per-application domain basis. This can reduce the number of collisions and improve the overall performance of insertions and lookups that use hash tables. The following example shows how to use the <UseRandomizedStringHashAlgorithm> element. It defines a DisplayString class that includes a private string constant, s, whose value is "This is a string." It also includes a ShowStringHashCode method that displays the string value and its hash code along with the name of the application domain in which the method is executing.

using System;public class Example{ public static void Main() { // Show hash code in current domain. DisplayString display = new DisplayString(); display.ShowStringHashCode(); // Create a new app domain and show string hash code. AppDomain domain = AppDomain.CreateDomain("NewDomain"); var display2 = (DisplayString) domain.CreateInstanceAndUnwrap(typeof(Example).Assembly.FullName, "DisplayString"); display2.ShowStringHashCode(); }}public class DisplayString : MarshalByRefObject{ private String s = "This is a string."; public override bool Equals(Object obj) { String s2 = obj as String; if (s2 == null) return false; else return s == s2; } public bool Equals(String str) { return s == str; } public override int GetHashCode() { return s.GetHashCode(); } public override String ToString() { return s; } public void ShowStringHashCode() { Console.WriteLine("String '{0}' in domain '{1}': {2:X8}", s, AppDomain.CurrentDomain.FriendlyName, s.GetHashCode()); }}
open Systemtype DisplayString() = inherit MarshalByRefObject() let s = "This is a string." override _.Equals(obj) = match obj with | :? string as s2 -> s = s2 | _ -> false member _.Equals(str) = s = str override _.GetHashCode() = s.GetHashCode() override _.ToString() = s member _.ShowStringHashCode() = printfn $"String '{s}' in domain '{AppDomain.CurrentDomain.FriendlyName}': {s.GetHashCode():X8}"// Show hash code in current domain.let display = DisplayString()display.ShowStringHashCode()// Create a new app domain and show string hash code.let domain = AppDomain.CreateDomain "NewDomain"let display2 = domain.CreateInstanceAndUnwrap(typeof<DisplayString>.Assembly.FullName, "DisplayString") :?> DisplayString display2.ShowStringHashCode()
Module Example Public Sub Main() ' Show hash code in current domain. Dim display As New DisplayString() display.ShowStringHashCode() ' Create a new app domain and show string hash code. Dim domain As AppDomain = AppDomain.CreateDomain("NewDomain") Dim display2 = CType(domain.CreateInstanceAndUnwrap(GetType(Example).Assembly.FullName, "DisplayString"), DisplayString) display2.ShowStringHashCode() End SubEnd ModulePublic Class DisplayString : Inherits MarshalByRefObject Private s As String = "This is a string." Public Overrides Function Equals(obj As Object) As Boolean Dim s2 As String = TryCast(obj, String) If s2 Is Nothing Then Return False Else Return s = s2 End If End Function Public Overloads Function Equals(str As String) As Boolean Return s = str End Function Public Overrides Function GetHashCode() As Integer Return s.GetHashCode() End Function Public Overrides Function ToString() As String Return s End Function Public Sub ShowStringHashCode() Console.WriteLine("String '{0}' in domain '{1}': {2:X8}", s, AppDomain.CurrentDomain.FriendlyName, s.GetHashCode()) End SubEnd Class

When you run the example without supplying a configuration file, it displays output similar to the following. Note that the hash codes for the string are identical in the two application domains.

String 'This is a string.' in domain 'PerDomain.exe': 941BCEACString 'This is a string.' in domain 'NewDomain': 941BCEAC

However, if you add the following configuration file to the example's directory and then run the example, the hash codes for the same string will differ by application domain.

<?xml version ="1.0"?><configuration> <runtime> <UseRandomizedStringHashAlgorithm enabled="1" /> </runtime></configuration>

When the configuration file is present, the example displays the following output:

String 'This is a string.' in domain 'PerDomain.exe': 5435776DString 'This is a string.' in domain 'NewDomain': 75CC8236

Important

Hash codes are used to insert and retrieve keyed objects from hash tables efficiently. However, hash codes don't uniquely identify strings. Identical strings have equal hash codes, but the common language runtime can also assign the same hash code to different strings. In addition, hash codes can vary by version of .NET, by platform within a single version, and by application domain. Because of this, you should not serialize or persist hash code values, nor should you use them as keys in a hash table or dictionary.

For additional information about the use of hash codes and the GetHashCode method, see Object.GetHashCode.

Notes to Callers

The value returned by GetHashCode() is platform-dependent. It differs on the 32-bit and 64-bit versions of .NET Framework. It also can differ between versions of .NET Framework and .NET Core.

See also

  • GetHashCode()
  • <UseRandomizedStringHashAlgorithm> Element

Applies to

String.GetHashCode Method (System) (2024)
Top Articles
Need support staff at your civil engineering firm? The shortage is real
Frozen: Ice on Earth and Well Beyond - NASA Science
Basic Setup – OpenXR & Pimax HMDs...
Top 5 Linux Distributions to Try the KDE Plasma 6 Desktop Right Now - 9to5Linux
Craigslist Mount Pocono
The Sacred Ashes Grim Dawn
Csulb Financial Aid Office Hours
3466051968
Anastasiya Kvitko Forum
Strange World Showtimes Near Cec - Cinema West Theatre
Les 3 meilleurs bivy-bags pour le bikepacking en 2023
Thothut
Pollen Count In Brandon Fl
M3Gan Showtimes Near Regal City North
Becker-Hunt Funeral Home Obituaries
Alex Bodger Stab Video
Rent A Stump Grinder Menards
Family Security Credit Union Gardendale
Subway Surfers Unblocked Wtf
Netherlands Toys, Games & Hobbies | ExpatINFO Holland
Opel Rocks-e im Test: Cooler Köder
Flower Mound Distal Radius Fracture
Csusm Verify My Fafsa
Scammer phone number lookup. How to check if a phone number is a scam
فیلم پیشنهاد بی شرمانه دوبله فارسی نماشا بدون سانسور
USAA hiring Inside Property Adjuster - Local CAT Team in Tampa, FL | LinkedIn
Zuercher Portal Inmates Clinton Iowa
Does Nutrisystem Take Ebt
Weilers Gentle Giants
043300109264
Marshall School District (2024-25) - Marshall, MO
Covenant Funeral Service Stafford Obituaries
The Review Online East Liverpool
Shapers Stars
Pennywise The Clown Wiki
Wv Mugshots 2023
Sandwich Based Flavor Of Lays Crossword
Haunted Mansion (2023) | Rotten Tomatoes
BBC - History World Wars: The Allies at War
Hatcher Funeral Home Aiken Sc
Application guide for first-year students
M3Gan Showtimes Near Cinemark Buckland Hills 18 + Imax
Nba Draftkings Picks For Tonight Cbs
Aeries Birmingham Portal
Craigslist Lake Charles
Cvs Minuteclinic Locations Near Me
Mydocbill.com/Mr
Atliens Hip Hop Duo Crossword
R/Mcoc
Carthage Women's Soccer Roster
Joplin.craigslist
Star Citizen 2024 Review - Is it worth buying? - Gamers By Night
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5444

Rating: 4.1 / 5 (42 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.