Questions tagged [gethashcode]

GetHashCode is method of base Object class of .Net Framework.

gethashcode
Filter by
Sorted by
Tagged with
1676 votes
22 answers
297k views

What is the best algorithm for overriding GetHashCode?

In .NET, the GetHashCode method is used in a lot of places throughout the .NET base class libraries. Implementing it properly is especially important to find items quickly in a collection or when ...
bitbonk's user avatar
  • 49.2k
198 votes
7 answers
76k views

Default implementation for Object.GetHashCode()

How does the default implementation for GetHashCode() work? And does it handle structures, classes, arrays, etc. efficiently and well enough? I am trying to decide in what cases I should pack my own ...
Fung's user avatar
  • 7,660
163 votes
3 answers
42k views

What's the role of GetHashCode in the IEqualityComparer<T> in .NET?

I'm trying to understand the role of the GetHashCode method of the interface IEqualityComparer. The following example is taken from MSDN: using System; using System.Collections.Generic; class ...
Lucian's user avatar
  • 3,971
139 votes
11 answers
158k views

.NET unique object identifier

Is there a way of getting a unique identifier of an instance? GetHashCode() is the same for the two references pointing to the same instance. However, two different instances can (quite easily) get ...
Martin Konicek's user avatar
128 votes
3 answers
183k views

Correct way to override Equals() and GetHashCode() [duplicate]

I have never really done this before so i was hoping that someone could show me the correct what of implementing a override of Except() and GetHashCode() for my class. I'm trying to modify the class ...
Nugs's user avatar
  • 5,643
71 votes
2 answers
41k views

Does String.GetHashCode consider the full string or only part of it?

I'm just curious because I guess it will have impact on performance. Does it consider the full string? If yes, it will be slow on long string. If it only consider part of the string, it will have bad ...
Louis Rhys's user avatar
  • 35.1k
62 votes
3 answers
21k views

How do I create a HashCode in .net (c#) for a string that is safe to store in a database?

To quote from Guidelines and rules for GetHashCode by Eric Lippert: Rule: Consumers of GetHashCode cannot rely upon it being stable over time or across appdomains Suppose you have a Customer ...
Ian Ringrose's user avatar
  • 51.5k
61 votes
5 answers
12k views

Overriding GetHashCode for mutable objects?

I've read about 10 different questions on when and how to override GetHashCode but there's still something I don't quite get. Most implementations of GetHashCode are based on the hash codes of the ...
Davy8's user avatar
  • 31.2k
57 votes
5 answers
26k views

Is there a complete IEquatable implementation reference?

Many of my questions here on SO concerns IEquatable implementation. I found it being extremely difficult to implement correctly, because there are many hidden bugs in the naïve implementation, and the ...
Jader Dias's user avatar
  • 89.3k
53 votes
7 answers
19k views

What's the best strategy for Equals and GetHashCode?

I'm working with a domain model and was thinking about the various ways that we have to implement these two methods in .NET. What is your preferred strategy? This is my current implementation: ...
tucaz's user avatar
  • 6,624
49 votes
11 answers
8k views

General advice and guidelines on how to properly override object.GetHashCode()

According to MSDN, a hash function must have the following properties: If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do ...
46 votes
4 answers
40k views

Good GetHashCode() override for List of Foo objects respecting the order

EnumerableObject : IEnumerable<Foo> wraps a List<Foo> If EnumerableObject a.SequenceEquals( EnumerableObject b), then they are equal. Therefore, a GetHashCode must be implemented. The ...
Ben B.'s user avatar
  • 3,756
44 votes
6 answers
4k views

Why might a System.String object not cache its hash code?

A glance at the source code for string.GetHashCode using Reflector reveals the following (for mscorlib.dll version 4.0): public override unsafe int GetHashCode() { fixed (char* str = ((char*) ...
Dan Tao's user avatar
  • 127k
39 votes
2 answers
4k views

Why do string hash codes change for each execution in .NET?

Consider the following code: Console.WriteLine("Hello, World!".GetHashCode()); First run: 139068974 Second run: -263623806 Now consider the same thing written in Kotlin: println("...
Matthew Layton's user avatar
38 votes
7 answers
8k views

C#: How would you unit test GetHashCode?

Testing the Equals method is pretty much straight forward (as far as I know). But how on earth do you test the GetHashCode method?
Svish's user avatar
  • 155k
36 votes
6 answers
60k views

Overriding GetHashCode [duplicate]

As you know, GetHashCode returns a semi-unique value that can be used to identify an object instance in a collection. As a good practice, it is recommended to override this method and implement your ...
Den's user avatar
  • 16.7k
36 votes
2 answers
16k views

String.GetHashCode() returns different values

Why is GetHashCode() returning a different value for the same string? I can't describe how to duplicate this, but trust that this is not a practical joke and that the two following lines came from my ...
Mark J Miller's user avatar
32 votes
7 answers
27k views

Using GetHashCode for getting Enum int value

I have an enum public enum INFLOW_SEARCH_ON { ON_ENTITY_HANDLE = 0, ON_LABEL = 1, ON_NODE_HANDLE = 2 } // enum INFLOW_SEARCH_ON I have to use this enum ...
Mohit Vashistha's user avatar
31 votes
1 answer
9k views

How to use System.HashCode.Combine with more than 8 values?

.NET Standard 2.1 / .NET Core 3 introduce System.HashCode to quickly combine fields and values to a hash code without having to care about the underlying implementation. However, it only provides ...
Ray's user avatar
  • 8,444
30 votes
4 answers
14k views

implement GetHashCode() for objects that contain collections

Consider the following objects: class Route { public int Origin { get; set; } public int Destination { get; set; } } Route implements equality operators. class Routing { public List<...
Joanna Derks's user avatar
  • 4,053
29 votes
7 answers
9k views

Overriding GetHashCode in VB without checked/unchecked keyword support?

So I'm trying to figure out how to correctly override GetHashCode() in VB for a large number of custom objects. A bit of searching leads me to this wonderful answer. Except there's one problem: VB ...
Kumba's user avatar
  • 2,398
28 votes
5 answers
10k views

Why is ValueType.GetHashCode() implemented like it is?

From ValueType.cs **Action: Our algorithm for returning the hashcode is a little bit complex. We look ** for the first non-static field and get it's hashcode. If the type has no ** ...
alh84001's user avatar
  • 1,273
27 votes
3 answers
20k views

What should GetHashCode return when object's identifier is null?

Which of the following is correct/better, considering that identity property could be null. public override int GetHashCode() { if (ID == null) { return base.GetHashCode(); } ...
Dienekes's user avatar
  • 1,548
26 votes
4 answers
16k views

What is the difference between using IEqualityComparer and Equals/GethashCode Override?

When i am using dictionaries sometimes I have to change the default Equals meaning in order to compare Keys. I see that if I override the Equals and GetHashCode on the key's class or i create a new ...
dariush624's user avatar
24 votes
4 answers
30k views

Generate integer based on any given string (without GetHashCode)

I'm attempting to write a method to generate an integer based on any given string. When calling this method on 2 identical strings, I need the method to generate the same exact integer both times. I ...
mrb398's user avatar
  • 1,287
23 votes
2 answers
5k views

Do I need to override GetHashCode() on reference types?

I read most questions on StackOverflow with regards to GetHashCode. But I am still not sure whether I have to override GetHashCode on reference types. I picked up the following from someones answer in ...
user avatar
22 votes
2 answers
22k views

GetHashCode on null fields?

How do I deal with null fields in GetHashCode function? Module Module1 Sub Main() Dim c As New Contact Dim hash = c.GetHashCode End Sub Public Class Contact : Implements IEquatable(Of ...
Shimmy Weitzhandler's user avatar
22 votes
7 answers
13k views

Why does C# not implement GetHashCode for Collections?

I am porting something from Java to C#. In Java the hashcode of a ArrayList depends on the items in it. In C# I always get the same hashcode from a List... Why is this? For some of my objects the ...
Peterdk's user avatar
  • 15.8k
21 votes
3 answers
9k views

C# how to calculate hashcode from an object reference

Folks, here's a thorny problem for you! A part of the TickZoom system must collect instances of every type of object into a Dictionary<> type. It is imperative that their equality and hash code ...
Wayne's user avatar
  • 2,969
20 votes
1 answer
14k views

Persistent hashcode for strings [duplicate]

I want to generate an integer hashcode for strings, that will stay constant forever; i.e. the same string should always result in the same hashcode. The hash does not have to be cryptographically ...
HugoRune's user avatar
  • 13.4k
20 votes
3 answers
11k views

Object.GetHashCode

My question may duplicate Default implementation for Object.GetHashCode() but I'm asking again because I didn't understand the accepted answer to that one. To begin with I have three questions about ...
ChrisW's user avatar
  • 55.4k
20 votes
3 answers
5k views

Overriding GetHashCode()

In this article, Jon Skeet mentioned that he usually uses this kind of algorithm for overriding GetHashCode(). public override int GetHashCode() { unchecked // Overflow is fine, just wrap { ...
Pacane's user avatar
  • 20.9k
19 votes
2 answers
12k views

Will string.GetHashCode() return negative value?

I tried with batch of random strings, all values I got are positive, but I wondering: Will String.GetHashCode() return negative or 0? Since the return value is int, so I guess it might be, so if it ...
Eric Yin's user avatar
  • 8,853
18 votes
4 answers
9k views

GetHashCode() gives different results on different servers?

I declared a C# line of code like so int hashcode = "apple".GetHashCode(); On my computer, a computer at work, and a friend's computer, the result was 1657858284. On a development server, the ...
learningtech's user avatar
17 votes
4 answers
6k views

Is it possible to combine hash codes for private members to generate a new hash code?

I have an object for which I want to generate a unique hash (override GetHashCode()) but I want to avoid overflows or something unpredictable. The code should be the result of combining the hash ...
Adrian Hope-Bailie's user avatar
17 votes
3 answers
7k views

Equals vs GetHashCode when comparing objects

Should we override both Equals and GetHashCode properties when implementing a custom class instances comparison? In the following code I have a collection of classes. The class A is compared by the ...
serhio's user avatar
  • 28.3k
16 votes
3 answers
35k views

Seeding a pseudo-random number generator in C#

I need a seed for an instance of C#'s Random class, and I read that most people use the current time's ticks counter for this. But that is a 64-bit value and the seed needs to be a 32-bit value. Now I ...
Daniel A.A. Pelsmaeker's user avatar
16 votes
4 answers
10k views

When Should a .NET Class Override Equals()? When Should it Not?

The VS2005 documentation Guidelines for Overloading Equals() and Operator == (C# Programming Guide) states in part Overriding operator == in non-immutable types is not recommended. The newer .NET ...
Eric J.'s user avatar
  • 149k
16 votes
1 answer
2k views

Implementation of Object.GetHashCode()

I'm reading Effective C# and there is a comment about Object.GetHashCode() that I didn't understand: Object.GetHashCode() uses an internal field in the System.Object class to generate the hash ...
Belgi's user avatar
  • 14.8k
15 votes
5 answers
19k views

GetHashCode() with string keys

Hey all, I've been reading up on the best way to implement the GetHashCode() override for objects in .NET, and most answers I run across involve somehow munging numbers together from members that are ...
King Skippus's user avatar
  • 3,816
15 votes
6 answers
10k views

Generic IEqualityComparer<T> and GetHashCode

Being somewhat lazy about implementing lots of IEqualityComparers, and given that I couldn't easily edit class implementations of the objects being compared, I went with the following, meant to be ...
mathieu's user avatar
  • 31.1k
15 votes
4 answers
4k views

new KeyValuePair<UInt32, UInt32>(i, j).GetHashCode(); High Rate of Duplicates

In search of a fast composite key for Dictionary I came upon anomaly I cannot understand nor justify. In limited testing Dictionary<KeyValuePair<UInt32, UInt32>, string> is ...
paparazzo's user avatar
  • 44.8k
15 votes
1 answer
678 views

Two equal IPv6 IPAddress instances return different GetHashCode results

I have two clients that create IPAddress instances from the same byte[] and send it to the server over WCF (using DataContractSerializer). On the server, these IPAddress instances are inserted as ...
Sivan Krigsman's user avatar
14 votes
2 answers
1k views

GetHashCode and Equals are implemented incorrectly in System.Attribute?

Seeing from Artech's blog and then we had a discussion in the comments. Since that blog is written in Chinese only, I'm taking a brief explanation here. Code to reproduce: [AttributeUsage(...
Cheng Chen's user avatar
  • 43.1k
13 votes
5 answers
3k views

What to return when overriding Object.GetHashCode() in classes with no immutable fields?

Ok, before you get all mad because there are hundreds of similar sounding questions posted on the internet, I can assure you that I have just spent the last few hours reading all of them and have not ...
Sheridan's user avatar
  • 69.4k
13 votes
1 answer
1k views

Is the .Net HashSet uniqueness calculation completely based on Hash Codes?

I was wondering whether the .Net HashSet<T> is based completely on hash codes or whether it uses equality as well? I have a particular class that I may potentially instantiate millions of ...
RobV's user avatar
  • 28.3k
12 votes
9 answers
7k views

GetHashCode Extension Method

After reading all the questions and answers on StackOverflow concerning overriding GetHashCode() I wrote the following extension method for easy and convenient overriding of GetHashCode(): public ...
user avatar
11 votes
7 answers
8k views

GetHashCode() problem using xor

My understanding is that you're typically supposed to use xor with GetHashCode() to produce an int to identify your data by its value (as opposed to by its reference). Here's a simple example: class ...
Jon B's user avatar
  • 51.4k
11 votes
5 answers
2k views

Why use GetHashCode() over Equals()?

HashSet<T>.Add first compares the results of GetHashCode. If those are equal, it calls Equals. Now, my understanding is in order to implement GetHashCode, something must be done with the fields ...
user247702's user avatar
11 votes
2 answers
2k views

Library with Equals and GetHashCode helper methods for .NET

Google Guava provides nice helpers to implement equals and hashCode like the following example demonstrates: public int hashCode() { return Objects.hashCode(lastName, firstName, gender); } Is ...
deamon's user avatar
  • 90.6k

1
2 3 4 5
7