Get the hash code for the current Decimal instance in C#

The GetHashCode() method in C# returns a 32-bit signed integer hash code for the current Decimal instance. This hash code is used internally by collections like HashSet and Dictionary to efficiently store and retrieve decimal values.

Hash codes are essential for the proper functioning of hash-based collections, as they provide a quick way to categorize and locate objects. Two Decimal instances that are equal will always return the same hash code, but different decimal values may occasionally produce the same hash code (hash collision).

Syntax

Following is the syntax for getting the hash code of a Decimal instance −

public override int GetHashCode();

Return Value

The method returns an int representing the hash code for the current Decimal instance.

Using GetHashCode() with Regular Decimal Values

Example

using System;
public class Demo {
   public static void Main(){
      Decimal val = 135269.38193M;
      Console.WriteLine("Decimal Value = {0}", val);
      Console.WriteLine("HashCode = {0}", (val.GetHashCode()) );
   }
}

The output of the above code is −

Decimal Value = 135269.38193
HashCode = 1328665595

Using GetHashCode() with Decimal.MaxValue

Example

using System;
public class Demo {
   public static void Main(){
      Decimal val = Decimal.MaxValue;
      Console.WriteLine("Decimal Value = {0}", val);
      Console.WriteLine("HashCode = {0}", (val.GetHashCode()) );
   }
}

The output of the above code is −

Decimal Value = 79228162514264337593543950335
HashCode = 1173356544

Comparing Hash Codes of Equal Decimal Values

Example

using System;
public class Demo {
   public static void Main(){
      Decimal val1 = 123.45M;
      Decimal val2 = 123.45M;
      Decimal val3 = 123.46M;
      
      Console.WriteLine("val1 = {0}, HashCode = {1}", val1, val1.GetHashCode());
      Console.WriteLine("val2 = {0}, HashCode = {1}", val2, val2.GetHashCode());
      Console.WriteLine("val3 = {0}, HashCode = {1}", val3, val3.GetHashCode());
      
      Console.WriteLine("val1 equals val2: {0}", val1.Equals(val2));
      Console.WriteLine("Hash codes equal: {0}", val1.GetHashCode() == val2.GetHashCode());
   }
}

The output of the above code is −

val1 = 123.45, HashCode = 1991951045
val2 = 123.45, HashCode = 1991951045
val3 = 123.46, HashCode = 1991951046
val1 equals val2: True
Hash codes equal: True

Conclusion

The GetHashCode() method returns a hash code for Decimal instances, which is essential for hash-based collections. Equal decimal values always produce the same hash code, making this method reliable for use in Dictionary and HashSet operations.

Updated on: 2026-03-17T07:04:36+05:30

203 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements