Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do "int" and "sbyte" GetHashCode functions generate different values?

Tags:

c#

hash

We have the following code:

int i = 1;
Console.WriteLine(i.GetHashCode());  // outputs => 1

This make sense and the same happen whit all integral types in C# except sbyte and short. That is:

sbyte i = 1;
Console.WriteLine(i.GetHashCode());   //  outputs => 257

Why is this?

like image 487
Eric Javier Hernandez Saura Avatar asked Sep 19 '12 19:09

Eric Javier Hernandez Saura


1 Answers

Because the source of that method (SByte.GetHashCode) is

public override int GetHashCode()
{
    return (int)this ^ ((int)this << 8);
}

As for why, well someone at Microsoft knows that..

like image 163
harold Avatar answered Sep 28 '22 17:09

harold