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 mouseLeftPressed    = 0b0000010;
const mouseLeftReleased   = 0b0000100;
const mouseRightPressed   = 0b0001000;
const mouseRightReleased  = 0b0010000;
const mouseMiddlePressed  = 0b0100000;
const mouseMiddleReleased = 0b1000000;
C#
const mouseLeftPressed    = 0x001; // Bit 1
const mouseLeftReleased   = 0x004; // Bit 2
const mouseRightPressed   = 0x008; // Bit 3
const mouseRightReleased  = 0x010; // Bit 4
const mouseMiddlePressed  = 0x020; // Bit 5
const mouseMiddleReleased = 0x040; // Bit 6

Notes

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

More information