Formatting numeric literals using digit separators in C#

Jul 14, 2021 by Kolappan N

I came to know about this just recently that you can format the number in your declaration statement in C#. It is a really nice trick. This feature was first introduced in C# 7 and it allows you to use underscore as a digit separator. The underscore will act like how you use comma in the real world and it won’t change the value of the number.

long contactNumber1 = 9876543210;
long contactNumber2 = 98_765_43_210;
long contactNumber3 = 98765_43210;
if(contactNumber1 == contactNumber2 && contactNumber1 == contactNumber3){
    Console.WriteLine("True");
}

The above code will print True on the console as the underscore is only for visual identification and has no bearing on the value. It can be used to format any numeric type from int to long. Another thing to note here is that you cannot have the underscore on the start or at the end of the number.

Further Reading:

  1. Digit Separator | C# 7 Spec
  2. Digit Separator | C# 7.2 Update
Tags: C Sharp