0

Recently I came across a code base and found some code like below

var a = 1_23_456;
Console.WriteLine(a); 

I have tried to run it in visual studio 2015/ .net fiddle but it got a compilation error. But when I retried it using Roslyn 2.0 compiler, it got compiled and gives me the output 123456.

What the matter here? Why it is showing the data as an integer ?

Noor A Shuvo
  • 2,639
  • 3
  • 23
  • 48
  • 13
    That's a C# 7 feature. It allows you to put a `_` in a number as a way to group digits. You need VS 2017 to compile it. See the "Literal Improvements" section in this blog post. https://blogs.msdn.microsoft.com/dotnet/2017/03/09/new-features-in-c-7-0/ – vcsjones Aug 28 '17 at 13:40
  • Try `Console.WriteLine(a.GetType());` to find out (spoiler: this is an `int`, AKA `System.Int32`) – Sergey Kalinichenko Aug 28 '17 at 13:41
  • Btw: [fiddle](https://dotnetfiddle.net/BuljEh) supports Roslyn 2.0. – Sinatr Aug 28 '17 at 13:45
  • Reflector sees a syntax error but VS2017 compiles and runs without problem. Didn't know it works – Tim Schmelter Aug 28 '17 at 13:45
  • 1
    Again a feature to produce unreadable code: `var DexterityAndStrengthAndLife = 12_23_100`. No idea why one would put different data into a single number, besides some memory-issues. – MakePeaceGreatAgain Aug 28 '17 at 13:55
  • 1
    @HimBromBeere, that's another question. And the answer is indeed less memory (namely [packed values](https://en.wikipedia.org/wiki/Binary-coded_decimal)) and even some performance gain (e.g. single add operation with two and two packed values). Multiply this by millions (e.g. in game AI). This feature is quite useful for binary literals. – Sinatr Aug 28 '17 at 14:08

1 Answers1

4

The underscores are the digit separator. They're used to make it easier to read large numbers (particularly binary numbers). You can read about them on MSDN.

The underscores don't change the datatype. All of the following statements result in the same data type (int or System.Int32) and value:

var a = 123456;
int b = 123456;
System.Int32 c = 123456;
var d = 1_23_456;
int e = 1_23_456;
System.Int32 f = 1_23_456;

You will need the new compiler in Visual Studio 2017 to compile it, though you may be able to get away with using Visual Studio 2015.

mason
  • 31,774
  • 10
  • 77
  • 121
  • Got it :). It improves the readability. Are there any other technical benefits to group digits in a number? Just curious. – Noor A Shuvo Aug 28 '17 at 13:51
  • @NoorAShuvo No technical benefits, just readability. They're particularly useful for dealing with binary or hex. – mason Aug 28 '17 at 13:52