Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetHashCode() with ^

Tags:

c#

c#-4.0

Does it have some special meaning when GetHashCode() function returns something using code which contains ^ symbol?

public class ClassProp
{
    public int Prop1 { get; set; }
    public int Prop2 { get; set; }
    public int Prop3 { get; set; }
    public int Prop4 { get; set; }
    public int Prop5 { get; set; }

    public override int GetHashCode()
    {
        return Prop1.GetHashCode() ^ Prop2.GetHashCode() ^ 
               Prop3.GetHashCode() ^ Prop4.GetHashCode() ^ Prop5.GetHashCode();
    }
}
like image 725
Nilish Avatar asked May 22 '12 16:05

Nilish


People also ask

What is gethashcode in Java?

A hash code is a numeric value which is used to insert and identify an object in a hash-based collection. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

Does gethashcode () method throw exceptions?

The GetHashCode () method should not throw exceptions. For example, the implementation of the GetHashCode () method provided by the String class returns identical hash codes for identical string values. Therefore, two String objects return the same hash code if they represent the same string value.

How to calculate the hash code of an object?

The main points to take into consideration when calculating the hash code are: 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.

How do I get the hash code of a 32 bit integer?

Int32.GetHashCode Method in C# with Examples. Int32.GetHashCode method is used to get the HashCode for the current Int32 instance. Syntax: public override int GetHashCode (); Return Value: This method returns a 32-bit signed integer hash code.


1 Answers

^ is the C# XOR operator. Nothing "special" about it, just that the hash codes of all the class properties are XOR'd together.

Edit: GetHashCode returns a generic code that is used as a shorthand identifier for a complex object. A common use is in hashing data structures when you want to store objects and then quickly retrieve them based on their hash code. Assume a class Person and some objects with the corresponding hash codes:

Alex 8540
John 9435
Peter 2453

These codes are generated based on some or all the fields of each object and must collide as rarely as possible to ensure efficient hashing. Now we can store the objects in a hash table using the hash code:

Entries
0 -> Alex
1 -> John
2 -> Peter

The objects are stored inside the table using their respective hash codes to determine the position. Next they can be easily retrieved by using the same hash code.

I suggest you find some literature about how hash tables work, because it's a bit too much to explain in an SO post.

like image 171
Tudor Avatar answered Nov 12 '22 20:11

Tudor