How is GetHashCode Implemented for Booleans?
Asked Answered
P

1

5

I was wondering how exactly they generate a hashcode from boolean types in C#/.NET?

Pridemore answered 2/4, 2016 at 14:40 Comment(3)
Simple. If the value is true, hashcode is 1, if the value is false, hashcode is 0.Nicholasnichole
@Nicholasnichole So something like : "return bool ? 1 : 0;"Pridemore
Exactly. But in the source, the 1 and 0 are defined as constants. referencesource.microsoft.com/#mscorlib/system/…Nicholasnichole
P
11

You can see the actual source code for .NET here, the implmentation for GetHashCode() for a bool is

  private bool m_value;

  internal const int True = 1; 
  internal const int False = 0; 

  public override int GetHashCode() {
      return (m_value)?True:False;
  }

(And yes, it is weird that System.Boolean contains a bool as a member variable, when the class is compiled the CLR treats the "primitive" types Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single special so they can do stuff like that)

Paddlefish answered 2/4, 2016 at 15:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.