Numeric Literals

When working with literals of a numeric type having large and complex number will be hard to read. For example, if we are assigning a large integer to say one million I.e.., 1000000  tailing 6 zeros to 1. Now if you see this number it will be very hard to read and the user should count the zero’s to know it a one million.

To solve this readable issue, a Literal (_) is now allowed in between the integer number to divide the digits from C# 7.0. Now, let’s see in practical implementation to understand this new feature.

Following is the implementation lines using C# 6.0

int cSharp6IntDemo = 100000; 
double cSharp6DoubleDemo = 12.45; 

Console.WriteLine(cSharp6IntDemo);  //output: 100000 
Console.WriteLine(cSharp6DoubleDemo); //output: 12.45 

Now, the same can be written in C# 7.0 by introducing this literal for better readable.

int cSharp7IntDemo = 1_00_000; 
double cSharp7DoubleDemo = 1_2_3.45_00; 

Console.WriteLine(cSharp7IntDemo);  //output: 100000 
Console.WriteLine(cSharp7DoubleDemo); //output: 123.4500

As you can observe in the above line of codes, we using literal (_) to separate the digits.

 Binary Literals

In C# 6.0, if you want to initialize a binary literal need to use hexadecimal notation as follows,

int hexFifteen = 0xF; 
int hexTwoFiftyFive = 0xFF; 

Console.WriteLine(hexFifteen);  //output: 15 
Console.WriteLine(hexTwoFiftyFive); //output: 255 

It is hard to decode hexadecimal notations. To solve this problem now from C# 7.0, you can use the binary bit literals itself by prefixing with ‘0b’ as follows.

int bitFifteen = 0b1111; 
int bitTwoFiftyFive = 0b1111_1111; 

Console.WriteLine(bitFifteen);  //output: 15 
Console.WriteLine(bitTwoFiftyFive); //output: 255 

Hope you understand this feature introduced from C# 7.0.

You can see complete code here in GitHub

Happy Coding 🙂