The digit separator feature is also introduced in C# 7.0. You can separate the large number into small parts making your code more readable using the digit separator.
_
) is used as a digit separator.Let's consider the following simple example without using digit separators.
long num1 = 1000000000000;
long num2 = 1000500000;
Console.WriteLine(num1);
Console.WriteLine(num2);
As you can that it is very difficult to read the exact value of num1
and num2
due to the large numerical literals. Now let's add the digit separators to the above example and see the readability.
long num1 = 1_000_000_000_000;
long num2 = 10_00_50_00_00;
Console.WriteLine(num1);
Console.WriteLine(num2);
As you can see, by adding the digit separator, you can have a great readability impact and no significant downside.
_
is allowed in decimals as well as exponents.You can use this separator with other numbers as well.
int bin = 0b1001__1010__0001__0100;
int hex = 0x1b_a0_44_fe;
int dec = 33_554_432;
double real = 1_000.111_1e-3;
ushort shortVal = 0b1011_1100_1011_0011;
Console.WriteLine(bin);
Console.WriteLine(hex);
Console.WriteLine(dec);
Console.WriteLine(real);
Console.WriteLine(shortVal);
The digit separator should not be used in the following places.
_1000_0000
1000_0000_
10_00_.03_33
1.1e_1
10_f
0b_1001_1000