How to provide hash code for each C# object

Hash code

Hash code is used by C# to distinguish one object from another. If two object represent two difference value they should have different hash code value.

Example

Example for GetHashCode Method


using System;/*ww  w  . ja  va  2 s.com*/

public class ComplexNumber
{
    public ComplexNumber( double real, double imaginary ) {
        this.real = real;
        this.imaginary = imaginary;
    }

    public override int GetHashCode() {
        return (int) Math.Sqrt( Math.Pow(this.real, 2) * Math.Pow(this.imaginary, 2) );
    }

    private readonly double real;
    private readonly double imaginary;
}




















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor