Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

double
c#
communitycreator

How to get the hash code of a double value in C#

Theodore Kelechukwu Onyejiaku

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 System
using System;
// create class
class DoubleHashCode
{
    // main method
    static void Main()
    {
        // create double values
        double d1 = 12.4545;
        double d2 = 23/74;
        double d3 = 89.323234;

        // get and print hash codes
        Console.WriteLine(d1.GetHashCode());
        Console.WriteLine(d2.GetHashCode());
        Console.WriteLine(d3.GetHashCode());
    }
}
Get the hash codes of double values

Explanation

  • Lines 10–12: We create and initialize some double variables.

  • Lines 15–17: We call the GetHashCode() method on the variables and print the results.

Example

// use System
using System;
// create class
class DoubleHashCode
{   
    // main method
    static void Main()
    {
      // create double values 
      double d1 = 12.485;
      double d2 = d1 * 1;

      // get and print hash codes
      Console.WriteLine(d1.GetHashCode());
      Console.WriteLine(d2.GetHashCode());
    }
}
Two equal double values have the same hash code

Explanation

  • Line 10–11 : We create two variables with same double values.

  • Line 14–15: The hash codes of the two double values 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.

RELATED TAGS

double
c#
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring