C# 7 Underscore as Digit Separator in Numeric Literals

C# 7 Underscore as Digit Separator in Numeric Literals

C# 7 has been released by Microsoft and can be found in Visual Studio 2017. Two C# 7 features I have already mentioned include C# 7 Tuples and C# 7 Local Functions, both of which I am very excited about as I use these features quite a bit in Python. Another new feature in C# 7, but less useful to me personally, is the ability to use an underscore as a digit separator in numeric literals in C# 7. This is visually appealing and makes it easier to read the value, whether this be in decimal, hexadecimal, or binary notation.

C# 7 _ as Digit Separator in Numeric Literals

Here is a bit of C# 7 code in Visual Studio 2017 that says it all. Notice the _ character when declaring numbers using decimal, hexadecimal, or binary notation. Although a subtle change the numbers are definitely easier to read.

// C# 7 Numeric Literal Improvements
// Use _ as separator inside numeric literals in C# 7.

// decimal notation
var balance = 2_435_951.68;
balance += 227_652;
Debug.WriteLine($"Balance = {balance}.");

// hexadecimal notation
var num = 0x01_00;
num += 1;
Debug.WriteLine($"num = {num}.");

// binary notation
var num2 = 0b1_0000_0000;
num2 += 1;
Debug.WriteLine($"num2 = {num2}.");

Python 3.6 Underscore as Digit Separator

What attracted my attention to using the underscore as a digit separtor in C# 7 is that this is also proposed and will be available in Python 3.6 ( PEP 515 ). Per the Python 3.6 Documentation: "PEP 515 adds the ability to use underscores in numeric literals for improved readability."

>>> 1_000_000_000_000_000
1000000000000000
>>> 0x_FF_FF_FF_FF
4294967295

I found it interesting that both C# 7 and Python 3.6 would be coming out with underscores as digit separators in numeric literals around the same time.

For presentation purposes, Python also allows the developer to specify an underscore in the display of numeric literals whether they be decimal, hexadecimal, or binary. This will be the thousands separator for decimals and every 4 digits for hexadecimal and binary numbers. Again, per the Python 3.6 Documentation:

>>> '{:_}'.format(1000000)
'1_000_000'
>>> '{:_x}'.format(0xFFFFFFFF)
'ffff_ffff'

I tried it, and don't see that C# 7 added a new format specifier to display the underscore in numeric values for presentation purposes.

Conclusion

If you add numeric literals to your C# 7 and Python 3.6 applications a lot, you will definitely appreciate the use of an underscore as a digit separator for numeric literals in decimal, hexadecimal, and binary notation. I don't do this a lot, but even in the simple examples above, underscores as digit separators are definitely easier to read and more visual appealing.

I'll be writing about more C# 7 Features, and as mentioned above, you can read some of my other C# 7 Tutorials: Tuples and Local Functions.