Numeric Literals And Binary Literals In C# 7.0

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

  1. int cSharp6IntDemo = 100000;   
  2. double cSharp6DoubleDemo = 12.45;   
  3.   
  4. Console.WriteLine(cSharp6IntDemo);  //output: 100000   
  5. Console.WriteLine(cSharp6DoubleDemo); //output: 12.45   

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

  1. int cSharp7IntDemo = 1_00_000;   
  2. double cSharp7DoubleDemo = 1_2_3.45_00;   
  3.   
  4. Console.WriteLine(cSharp7IntDemo);  //output: 100000   
  5. Console.WriteLine(cSharp7DoubleDemo); //output: 123.4500  

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.

  1. int hexFifteen = 0xF;   
  2. int hexTwoFiftyFive = 0xFF;   
  3.   
  4. Console.WriteLine(hexFifteen);  //output: 15   
  5. Console.WriteLine(hexTwoFiftyFive); //output: 255   

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.

  1. int bitFifteen = 0b1111;   
  2. int bitTwoFiftyFive = 0b1111_1111;   
  3.   
  4. Console.WriteLine(bitFifteen);  //output: 15   
  5. 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.