Skip to content

Binary literals C# 7.0readability

Allow binary values to be constants.

C# has allowed numeric constants since the start, either in decimal format like 10 or hex 0xA0.

With C# 7.0 binary constants are permitted so 0b1010 could also be used to represent this value if it made the meaning clearer.

Code

C#
const int mouseLeftPressed    = 0b0000010;
const int mouseLeftReleased   = 0b0000100;
const int mouseRightPressed   = 0b0001000;
const int mouseRightReleased  = 0b0010000;
const int mouseMiddlePressed  = 0b0100000;
const int mouseMiddleReleased = 0b1000000;
C#
const int mouseLeftPressed    = 0x002; // Bit 1
const int mouseLeftReleased   = 0x004; // Bit 2
const int mouseRightPressed   = 0x008; // Bit 3
const int mouseRightReleased  = 0x010; // Bit 4
const int mouseMiddlePressed  = 0x020; // Bit 5
const int mouseMiddleReleased = 0x040; // Bit 6

Notes

  • No binary format specifier exists
  • Use Convert.ToString(result, toBase: 2) to format as binary

More information