Reputation: 27019
In the code below what is the significance of underscores:
public const long BillionsAndBillions = 100_000_000_000;
Upvotes: 60
Views: 13839
Reputation: 3816
Allow me to digress a bit around more information here.
The number :
public const long BillionsAndBillions = 100_000_000_000;
Has got a nice readability, especially if we stick to "thousands", groups of three zeroes as much as possible for these large numbers. It is normal in several diciplines such as physics and economics to stick to "thousands", groups of three zeroes. This syntax is supported in C# 7.2, so that means it is supported in .NET Framework 4.6.1 or higher.
If you for some reason got even older framework in your code, the following syntax offers an alternative, it is supported from the very start of C# and .NET Framework 1:
public const long BillionsAndBillions = (long)1e11;
Also the syntax is more compact. Note that this e-notation is what you use in Physics to describe very large or very small numbers, and also other diciplines such as chemistry and economics and so on.
It is also less to type in many ranges starting to get a bit far above or below zero, and often many programmers are not familiar using it.
Please note that the e-notation returns a double, so the direct cast is used here. Sticking to double will be safer in many examples to avoid overflow.
Also, here is how you for example express large and small numbers:
EXAMPLES OF BIG AND SMALL NUMBERS USING E-Notation in C# :
double speedOfLightRoughly = 3e18 //300_000_000 meters per second - ca 1 x light speed
More accurately:
double speedOfLight = 2.99792458e8;
Avogadro's number used in chemistry :
double avogadrosNumber = 6.022e23;
And Stefan Boltzmann used in astronomy and thermodynamics
double stefanBoltzmannConstant = 5.670e-8; //small number : note e-notation with negative sign
Upvotes: 2
Reputation: 27019
This is a new feature of C# 7.0 and it is known as digit separator. The intent is to provide better and easier readability. It is mostly useful when writing numbers that are very long and hard to read in source code. For example:
long hardToRead = 9000000000000000000;
// With underscores
long easyToRead = 90000_00000_00000_0000;
It is totally up to the programmer on where to place the underscore. For example, you may have a weird scenario like this:
var weird = 1_00_0_0_000_0000000_0000;
public const decimal GoldenRatio = 1.618_033_988_749_894_848_204_586_834_365_638_117_720M;
Some Notes
As soon as you compile your code, the compiler removes the underscores so this is just for code readability. So the output of this:
public static void Main()
{
long easyToRead = 90000_00000_00000_0000;
Console.WriteLine(easyToRead);
}
will be (notice no underscores):
9000000000000000000
Here is a discussion about this feature when it was requested if you are interested. Some people wanted the separator to be blank spaces, but looks like the C# team went with underscores.
Upvotes: 95