How to get the hash code of a string in C#

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.

Syntax

ourString.GetHashCode()

Parameters

ourString: This is the string which we want to get hash code from.

Return value

This method returns the hash code of a string.

Code

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 class
class HashCode
{
// main method
static void Main()
{
// define and intialize our strings
string 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 above
int 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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources