Questions tagged [gethashcode]
GetHashCode is method of base Object class of .Net Framework.
gethashcode
342
questions
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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:
...
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 ...
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*) ...
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("...
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?
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 ...
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 ...
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 ...
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 ...
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<...
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 ...
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
** ...
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();
}
...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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
{
...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...
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(...
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 ...
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 ...
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 ...
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 ...
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 ...
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 ...