C# 7.0 – Literal improvements


Facebooktwittergoogle_pluslinkedinmail

C# 7.0 introduced nice improvements to literals. Both digit separator and binary literals can improve code readability.

Note: You can view all code examples on GitHub. My environment: Visual Studio 2017 and .NET Framework 4.6.1.

Digit separators

Big numbers in the code used to be not easy to process at first look. Seeing below code always makes me stop for a second and count digits.

        private void Example1()
        {
            int value = 25758345;
        }

Thanks to digit separators one can easily see the important pieces. Just place underscore (_) character between digits.

        private void Example2()
        {
            int value = 25_758_345;
        }

The only requirement is that digit separators have to be placed between digits. It’s not allowed to use them in the front or the end of literals. But one can use as many separators as needed.

        private void Example3()
        {
            int value1 = 25_75_83_45;
            int value2 = 25______7_5_8___________345;

            // Following will not compile
            // int value3 = _1234;
            // int value4 = 1234_;
        }

Binary literals

New C# introduces binary literals. This is very useful for defining binary masks. Previously the only option was to use hexadecimal notation.

        private void PrintValue(long value) => System.Console.WriteLine($"DEC={value} HEX={Convert.ToString(value, 16)} BIN={Convert.ToString(value, 2)}");

        private void Example4()
        {
            var hexMask1 = 0xDEAD_C0DE;
            var binaryMask1 = 0b1101_1110_1010_1101___1100_0000_1101_1110;
            PrintValue(hexMask1);
            PrintValue(binaryMask1);

            var hexMask2 = 0xBAD_C0FFEE;
            var binaryMask2 = 0b1011_1010_1101___1100_0000_1111_1111_1110_1110;
            PrintValue(hexMask2);
            PrintValue(binaryMask2);
        }

 

Facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *