Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the underscores mean in a numeric literal in C#?

Tags:

c#

In the code below what is the significance of underscores:

public const long BillionsAndBillions = 100_000_000_000;
like image 882
CodingYoshi Avatar asked Apr 18 '17 15:04

CodingYoshi


People also ask

Why and how underscores are defined in literals?

In Java SE 7 and later, any number of underscore characters ( _ ) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.

What is underscore in number?

When an underscore is placed before a number literal, it is interpreted as an identifier rather than a numeric literal. For example: int _10=0; , int x = _10; . When expecting a string with numbers, underscores can't be used. For example, Integer.

What are numeric separators?

A decimal separator is a symbol used to separate the integer part from the fractional part of a number written in decimal form (e.g., "." in 12.45). Different countries officially designate different symbols for use as the separator.

Are underscores allowed in Java?

Using underscore in a variable like first_name is still valid. But using _ alone as a variable name is no more valid. Even if you are using earlier versions of Java, using only underscore as a variable name is just a plain bad style of programming and must be avoided.


1 Answers

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

<==Try Me!==>

Here is a discussion about when this feature was requested if you are interested. Some people wanted the separator to be blank spaces, but looks like the C# team went with underscores.

like image 180
CodingYoshi Avatar answered Oct 19 '22 09:10

CodingYoshi