Numeric Literals
When working with literals of a numeric type, having a large and complex number is 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 has to count the zeros to know if it is 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 in order to understand this new feature.
Following is the implementation lines using C# 6.0
- int cSharp6IntDemo = 100000;
- double cSharp6DoubleDemo = 12.45;
-
- Console.WriteLine(cSharp6IntDemo);
- Console.WriteLine(cSharp6DoubleDemo);
Now, the same can be written in C# 7.0 by introducing this literal for better readability.
- int cSharp7IntDemo = 1_00_000;
- double cSharp7DoubleDemo = 1_2_3.45_00;
-
- Console.WriteLine(cSharp7IntDemo);
- Console.WriteLine(cSharp7DoubleDemo);
As you can observe in the above line of codes, we are using literal (_) to separate the digits.
Binary Literals
In C# 6.0, if you want to initialize a binary literal, you need to use hexadecimal notation as below.
- int hexFifteen = 0xF;
- int hexTwoFiftyFive = 0xFF;
-
- Console.WriteLine(hexFifteen);
- Console.WriteLine(hexTwoFiftyFive);
It is hard to decode the hexadecimal notations. To solve this problem, now from C# 7.0, you can use the binary bit literals by prefixing with '0b' as follows.
- int bitFifteen = 0b1111;
- int bitTwoFiftyFive = 0b1111_1111;
-
- Console.WriteLine(bitFifteen);
- Console.WriteLine(bitTwoFiftyFive);
Hope you understand this feature introduced from C# 7.0.
You can see complete code here in GitHub
Happy coding.