Getting the hash code of a string is simple in C#. We use the GetHashCode()
method.
A hash code is a uniquely identified numerical value. Note that strings that have the same value have the same hash code.
ourString.GetHashCode()
ourString
: This is the string which we want to get hash code from.
This method returns the hash code of a string.
In the example below, we will create a string with the string
object. We will also call the GetHashCode()
on these strings and pass the result to some integer variables. Finally, we will display these returned values to the console.
// create our classclass HashCode{// main methodstatic void Main(){// define and intialize our stringsstring name1 = "Theodore Onyejiaku";string role1 = "Software Developer";string name2 = "Kelechukwu Onyejiaku";string role2 = "Software Developer";string s1 = "Hello C#";string s2 = "Hello Edpresso!";// get hash codes of the strings aboveint a = name1.GetHashCode();int b = name2.GetHashCode();int c = role1.GetHashCode();int d = role2.GetHashCode();int e = s1.GetHashCode();int f = s2.GetHashCode();System.Console.WriteLine(a);System.Console.WriteLine(b);System.Console.WriteLine(c);System.Console.WriteLine(d);System.Console.WriteLine(e);System.Console.WriteLine(f);}}
From the code above, we see that the strings above have different hash codes, except for role1
and role
, which are the same because the string values are equal.