Using Digit Separators in C#: Enhancing Numeric Literal Readability

Learn how to improve the readability of numeric literals in C# using digit separators (underscores). This tutorial explains how to use underscores to separate digits in integers and floating-point numbers, enhancing code clarity without affecting their values.



Using Digit Separators in C#

What are Digit Separators?

Digit separators in C# (introduced in C# 7.0) improve the readability of numeric literals by allowing you to insert underscores (`_`) as separators between digits. This is particularly useful for large numbers, making it easier to visually parse and understand the value. The underscores are ignored by the compiler; they only affect the visual representation of the number.

Using Digit Separators in C#

To use digit separators, simply insert underscores between the digits of your numbers. This makes numbers easier to read, particularly large ones.

Example C# Code

int largeNumber = 1_000_000;
double anotherLargeNumber = 1_234_567.89;

The underscores improve readability without affecting the number's value. You can place underscores anywhere between digits (but not at the beginning or end of the number).

Example: Displaying Numbers with Separators

This example demonstrates using digit separators to display numbers. The output shows the numbers with underscores added for readability.

C# Code

using System;

public class DigitSeparatorExample {
    public static void Main(string[] args) {
        int i = 1_00_000;
        double f = 1_00_000.0;
        Console.WriteLine(i);
        Console.WriteLine(f);
    }
}

Conclusion

Digit separators are a simple yet effective feature in C# that enhance code readability without impacting functionality. They are particularly helpful for working with large numbers, improving code maintainability and reducing errors.