How to get the hash code of a double value in C#
Overview
The hash code of an object in C# is a unique numeric value. Objects that have the same value have the same hash code.
We get the hash code by the GetHashCode() method for double objects.
Syntax
public override int GetHashCode ();
Syntax for getting the hash code of a double value
Parameters
It takes no parameters. It is only called on a double instance.
Return value
A 32-bit signed integer value is returned.
Example
// use Systemusing System;// create classclass DoubleHashCode{// main methodstatic void Main(){// create double valuesdouble d1 = 12.4545;double d2 = 23/74;double d3 = 89.323234;// get and print hash codesConsole.WriteLine(d1.GetHashCode());Console.WriteLine(d2.GetHashCode());Console.WriteLine(d3.GetHashCode());}}
Explanation
-
Lines 10–12: We create and initialize some
doublevariables. -
Lines 15–17: We call the
GetHashCode()method on the variables and print the results.
Example
// use Systemusing System;// create classclass DoubleHashCode{// main methodstatic void Main(){// create double valuesdouble d1 = 12.485;double d2 = d1 * 1;// get and print hash codesConsole.WriteLine(d1.GetHashCode());Console.WriteLine(d2.GetHashCode());}}
Explanation
-
Line 10–11 : We create two variables with same
doublevalues. -
Line 14–15: The hash codes of the two
doublevalues are returned and printed to the console.
Note: As seen when the code is run, both variables return the same hash code. This is because they are equal.