New features of C × 8.0

Time:2021-3-24

readonly member

New features of C × 8.0New features of C × 8.0

        private struct Point
        {
            public Point(double x, double y)
            {
                X = x;
                Y = y;
            }

            private double X { get; set; }
            private double Y { get; set; }
            private readonly double Distance => Math.Sqrt(X * X + Y * Y);

            public override readonly string ToString() =>
                $"({X}, {Y}) is {Distance} from the origin";
        }

View Code

Modify the toString method with readonly to indicate that it is not modifiable

Default interface method

/// 
        ///Default interface method
        /// 
        private interface IWork
        {
            public void Work()
            {
                Console.WriteLine("Work");
            }
        }

Now you can define the default method in the interface instead of declaring void work ();

More pattern matching

Pattern matching using switch expression

New features of C × 8.0New features of C × 8.0

public enum Rainbow
            {
                Red,
                Orange,
                Yellow,
                Green,
                Blue,
                Indigo,
                Violet
            }

            //Switch expression
            public static Color FromRainbow(Rainbow colorBand) =>
                colorBand switch
                {
                    Rainbow.Red => Color.Red,
                    Rainbow.Orange => Color.Orange,
                    Rainbow.Yellow => Color.Yellow,
                    Rainbow.Green => Color.Green,
                    Rainbow.Blue => Color.Blue,
                    Rainbow.Indigo => Color.Indigo,
                    Rainbow.Violet => Color.Violet,
                    _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand)),
                };

View Code

Use the switch keyword after the variable, and replace case: with = >, using the_ Replace default

Attribute mode

New features of C × 8.0New features of C × 8.0

            public static decimal ComputeSalesTax(Address location, decimal salePrice) =>
                location switch
                {
                    { State: "WA" } => salePrice * 0.06M,
                    { State: "MN" } => salePrice * 0.075M,
                    { State: "MI" } => salePrice * 0.05M,
                    // other cases removed for brevity...
                    _ => 0M
                };

            public struct Address
            {
                public string State { get; set; }
            }

View Code

Pattern matching for the state attribute of location variable

Tuple pattern

New features of C × 8.0New features of C × 8.0

            public static string RockPaperScissors(string first, string second)
                => (first, second) switch
                {
                    ("rock", "paper") => "rock is covered by paper. Paper wins.",
                    ("rock", "scissors") => "rock breaks scissors. Rock wins.",
                    ("paper", "rock") => "paper covers rock. Paper wins.",
                    ("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
                    ("scissors", "rock") => "scissors is broken by rock. Rock wins.",
                    ("scissors", "paper") => "scissors cuts paper. Scissors wins.",
                    (_, _) => "tie"
                };

View Code

Location mode

New features of C × 8.0New features of C × 8.0

//Location pattern is a discrete variable that uses deconstruction to deconstruct attributes. If you can access the deconstruct method, you can use the location pattern to check the attributes of the object and use these attributes for the pattern
            public class XPoint
            {
                public int X { get; set; }
                public int Y { get; set; }

                public void Deconstruct(out int x, out int y)
                {
                    x = X;
                    y = Y;
                }
            }

            public int GetNumber(XPoint point) => point switch
            {
                (0, 0) => 0,
                var (x, y) when x > 0 && y > 0 => 1,
                var (x, y) when x < 0 && y > 0 => 2,
                var (x, y) when x < 0 && y < 0 => 3,
                var (x, y) when x > 0 && y < 0 => 4,
                var (_, _) => -1,
                _ => -2
            };

View Code

Using statement

/// 
        ///Using declaration, the operands of using expressions can implement IDisposable or iasyncdisposable
        /// 
        public void UsingStatement()
        {
            using var file = new System.IO.StreamWriter("WriteLines2.txt");
        }

Asynchronous releasable types can be released using the using keyword

Static local function

New features of C × 8.0New features of C × 8.0

/// 
        ///Static local function, using static keyword in local function
        /// 
        private class StaticLocalFunction
        {
            int N()
            {
                int y;
                LocalFunction();
                return y;

                void LocalFunction() => y = 0;
            }

            int M()
            {
                int y = 5;
                int x = 7;
                return Add(x, y);

                static int Add(int left, int right) => left + right;
            }
        }

View Code

You can use the static keyword in a local function declaration

Index and scope

New features of C × 8.0New features of C × 8.0

        private class IndexRange
        {
            string[] words = new string[]
            {
                // index from start    index from end
                "The",      // 0                   ^9
                "quick",    // 1                   ^8
                "brown",    // 2                   ^7
                "fox",      // 3                   ^6
                "jumped",   // 4                   ^5
                "over",     // 5                   ^4
                "the",      // 6                   ^3
                "lazy",     // 7                   ^2
                "dog"       // 8                   ^1
            };              // 9 (or words.Length) ^0

            void Test()
            {
                //>=index_1 && < index_4
                var quickBrownFox = words[1..4];
                var lazyDog = words[^2..^0];
            }
        }

View Code

Null merge assignment

/// 
        ///Null merge assignment
        /// 
        private void NullMergeAssignment()
        {
            List list = new List();
            List numbers = list.Where(x => x > 20).ToList();
            
            numbers ??= new List();
        }

When the left operand evaluates tonullWill??=The value of the right operand is assigned to the left

Asynchronous flow

New features of C × 8.0New features of C × 8.0

public static class AsyncStream
        {
            public static async System.Collections.Generic.IAsyncEnumerable GenerateSequence()
            {
                for (int i = 0; i < 20; i++)
                {
                    await Task.Delay(100);
                    yield return i;
                }
            }


            public static async void GetNumbers()
            {
                var c = CSharp8.AsyncStream.GenerateSequence();
                await foreach (var number in c)
                {
                    Console.WriteLine(number);
                }
            }
        }

View Code

Getnumbers uses await to wait for the returned result, and outputs the value of I + + every 100ms

Recommended Today

WWDC – Optimization of runtime

preface This optimization is proposed by wwdc-2020. You can watch the video by yourself: aboutruntimeImproved optimization of In the author’s words, developers do not need to change any code or use new APIs, and the application will become faster. becauseAppleIn the internal runtime, the underlying data structure is optimized. Class data structures changes On the […]