Skip to content

Binary literals C# 7.0readability

Allow numeric literals to be written in binary.

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

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

Code ​

csharp
const int mouseLeftPressed    = 0b0000010;
const int mouseLeftReleased   = 0b0000100;
const int mouseRightPressed   = 0b0001000;
const int mouseRightReleased  = 0b0010000;
const int mouseMiddlePressed  = 0b0100000;
const int mouseMiddleReleased = 0b1000000;
csharp
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 ​

  • Combine with Digit separators C# 7.0 to group bits, e.g. 0b0100_0000
  • .NET 8 and later support the B format specifier, e.g. value.ToString("B8")
  • On older runtimes use Convert.ToString(value, toBase: 2) to format as binary

More information ​

Powered by Intracia