C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# GetHashCode Method: Get The Hash Code

In this tutorial, we will explore the GetHashCode method in C#. The GetHashCode method is used to generate a hash code for an object, which is an integer that can be used to quickly determine whether two objects might be equal.

  • Understanding GetHashCode

The GetHashCode method is part of the Object class, which is the base class for all classes in C#. When you create a new class, it inherits the GetHashCode method from Object.

The default implementation of GetHashCode generates a hash code based on the object's reference. However, if you override the Equals method to provide custom equality logic, you should also override the GetHashCode method to generate a hash code based on the same logic.

  • Rules for GetHashCode

When implementing the GetHashCode method, you should follow these rules:

  • If two objects are equal (as determined by the Equals method), they must return the same hash code.
  • If two objects are not equal, they can return the same hash code, but it's better if they return different hash codes to minimize collisions.
  • The hash code for an object should not change during its lifetime, as long as the object's state that affects its equality does not change.
  • Overriding GetHashCode

Here's an example of a Person class that overrides both the Equals and GetHashCode methods:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
        {
            return false;
        }

        Person other = (Person)obj;
        return FirstName == other.FirstName
            && LastName == other.LastName
            && Age == other.Age;
    }

    public override int GetHashCode()
    {
        int hash = 17;
        hash = hash * 31 + (FirstName?.GetHashCode() ?? 0);
        hash = hash * 31 + (LastName?.GetHashCode() ?? 0);
        hash = hash * 31 + Age.GetHashCode();
        return hash;
    }
}

In this example, the GetHashCode method calculates a hash code based on the FirstName, LastName, and Age properties. The ?. operator is used to handle the case when a property is null.

  • Using GetHashCode

The GetHashCode method is often used by collection classes like HashSet<T> and Dictionary<TKey, TValue> to optimize their internal data structures:

HashSet<Person> people = new HashSet<Person>();
people.Add(new Person { FirstName = "John", LastName = "Doe", Age = 30 });
people.Add(new Person { FirstName = "Jane", LastName = "Doe", Age = 28 });

bool containsJohn = people.Contains(new Person { FirstName = "John", LastName = "Doe", Age = 30 });
Console.WriteLine(containsJohn); // Output: True

In this example, the HashSet<T> class uses the GetHashCode method to determine whether two Person objects might be equal, and then uses the Equals method to confirm their equality.

This tutorial demonstrates the basics of the GetHashCode method in C#. By overriding the GetHashCode method, you can ensure that your custom classes work correctly with collection classes and provide efficient hash-based lookups.

  1. How to use GetHashCode in C#:

    • Description: GetHashCode is a method in C# used to retrieve the hash code of an object, crucial for efficient use in hash-based collections.
    • Code:
      string myString = "C# HashCode";
      int hashCode = myString.GetHashCode();
      
  2. Override GetHashCode in C#:

    • Description: You can override GetHashCode to provide a custom implementation for calculating hash codes for objects.
    • Code:
      public override int GetHashCode()
      {
          // Custom hash code calculation
          return base.GetHashCode();
      }
      
  3. Implementing GetHashCode for custom classes in C#:

    • Description: For custom classes, implementing GetHashCode is crucial for proper functioning in hash-based collections.
    • Code:
      public class CustomClass
      {
          public override int GetHashCode()
          {
              // Custom hash code calculation
              return base.GetHashCode();
          }
      }
      
  4. Combining hash codes in C#:

    • Description: When implementing GetHashCode for composite objects, combine the hash codes of individual components.
    • Code:
      public override int GetHashCode()
      {
          int hash = 17;
          hash = hash * 23 + property1.GetHashCode();
          hash = hash * 23 + property2.GetHashCode();
          return hash;
      }