2

How can I make a large number more readable in code?

Right now I have:

long bigNumber = 11222333; //11,222,333

Commas in large numbers were invented a for a reason: readability. The best I can come up with is this:

long bigNumber = long.Parse("11,222,333");

However, it seems "wrong"

MikeH
  • 4,242
  • 1
  • 17
  • 32

1 Answers1

5

Hardcoded numbers should be avoided being explicitly in code, that's called Magic Number, instead you can have few possibilities marking the usage of that number.

Constants

public const int Megabyte = 1024 * 1024;
public const long Billion = 1000000000; // Or: (long)1E+9;

Enum

public enum MagicNumbers : long
{
    Billion = 1000000000
}

Underscored (C# 7), as @Lasse V. Karlsen mention in the comments.

long bigNumber = 11_222_333
Orel Eraki
  • 11,940
  • 3
  • 28
  • 36
  • I agree with the desire to avoid magic numbers. However, I usually like to supply default values in my classes to make implementation easier in "normal" cases. – MikeH Aug 16 '16 at 21:40