Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I declare constant integers with a thousands separator in C#?

Tags:

c#

constants

The Cobra programming language has a useful feature where you can use underscores in numeric literals to improve readability. For example, the following are equivalent, but the second line is easier to read:

x = 1000000
x = 1_000_000  # obviously 1 million

Is there anything equivalent for C#?

like image 473
Matthew Strawbridge Avatar asked Dec 13 '11 12:12

Matthew Strawbridge


2 Answers

Answer as of C# 7

Yes, this is supported in C# 7. But be aware that there's no validation that you've put the underscores in the right place:

// At a glance, this may look like a billion, but we accidentally missed a 0.
int x = 1_00_000_000;

Answer from 2011

No, there's nothing like that in C#. You could do:

const int x = 1000 * 1000;

but that's about as nice as it gets.

(Note that this enhancement went into Java 7 as well... maybe one day it will be introduced in C#.)

like image 99
Jon Skeet Avatar answered Nov 03 '22 13:11

Jon Skeet


Yes you can do this with C # 7.0 as shown here

public const long BillionsAndBillions = 100_000_000_000;
like image 7
CodingYoshi Avatar answered Nov 03 '22 15:11

CodingYoshi