Search code examples
c#booleangethashcode

How is GetHashCode Implemented for Booleans?


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


Solution

  • 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)