tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Lesser known feature of digit separators in C# 7

1 Mar 2018 2 mins C#

As I was on the .NET.CZ podcast I realized there’s maybe a one specific behavior of digit separators in C# 7 people might not be aware of.

Digit separators in C# 7

Digit separators were introduced in C# 7 and allows you to separate digits with _ (underscore) character. Together with binary literals (not only) this allows you to logically space some groups (4 bits, 8 bits, …). Here’s a small example with hexadecimal constant: var foo = 0xFF_00_DD;.

This feature was improved in C # 7.2 allowing you to have leading underscores. Building on previous example, this is allowed in C# 7.2: var foo = 0x_FF_00_DD;.

Specific behavior

Not only you can have a single separator between groups/digits, but you can have as much as you want. This allows you to format the literal even more.

Compare this example.

var a = 0b__10_11__11_01;
var b = 0b_10_11_11_01;

For me, the a is more readable. And if this is some kind of protocol, it might even nicely complement high/low bytes/words/…

var foo = 0b_01_11;
var bar = 0b_00_11;
var baz = 0b____11;

For me, the baz clearly tells only the 11 part is important. Rest is just “padding”.

Closing

We all lived without a digit separators feature, but I see it as a welcoming formatting/readability option especially for hexadecimal and binary literals. And ability to use multiple separators in sequence makes it even more useful.

Did you know about this?

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.