C ා 9.0 is finally here. Let’s take you to interpret the two new features of pattern matching and Nint

Time:2020-9-18

1: Background

1. Tell a story

I talked to you last timeTarget-typed newandLambda discard parametersI’m glad to see that the number of readers in the blog Garden and the company has reached a new high. No matter whether you are long or short on the new feature, at least you still have a very concerned attitude towards it. So my series has to follow. Let’s continue to introduce two new features, more new feature list, please pay attention to: preview of new features

2: Research on new characteristics

1. Native ints

From the literal point of view, what kind of native type ints seems to be, a little puzzling, or take a lookIssuesFor example:


Summary: nint i = 1; and nuint i2 = 2;

Shipped in preview in 16.7p1.

Interesting, or the first time to see such a thing Nint, should be cා9 new keywords, curiosity explosion, come to practice.


   static void Main(string[] args)
   {
        nint i = 10;
        Console.WriteLine($"i={i}");
   }

C ා 9.0 is finally here. Let's take you to interpret the two new features of pattern matching and Nint

From the figure, you can output as is, and then check the underlying IL code with ilspy. It is found that you don’t even need to look at the IL code. As shown in the figure below:

C ා 9.0 is finally here. Let's take you to interpret the two new features of pattern matching and Nint

From the picture, it turns out that Nint isIntPtrStructure ha, if you have played the interoperability between C ා and C + +, I believe you will be familiar with PTR, from thisnintDon’t you think that the C ᦇ team pays more attention to pointer operation than ever before? < / font > before pointer typeIntPtr, followed byMemory segment processing set spanNow, to provide keyword support directly is to do our best to let you use pointers under the premise of type safety.

This reminds me of an interoperability article I wrote a few days ago. Now we can simplify it with Nint. Let’s take a look at the code.

  • The original writing method is as follows:

        [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        extern static IntPtr AddPerson(Person person);

        static void Main(string[] args)
        {
            var person = new Person() { username = "dotnetfly", password = "123456" };
            var ptr = AddPerson(person);
            var str = Marshal.PtrToStringAnsi(ptr);
        }
  • How to write IntPtr > Nint

        [DllImport("ConsoleApplication1.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
        extern static nint AddPerson(Person person);

        static void Main(string[] args)
        {
            var person = new Person() { username = "dotnetfly", password = "123456" };
            nint ptr = AddPerson(person);
            var str = Marshal.PtrToStringAnsi(ptr);
        }

C ා 9.0 is finally here. Let's take you to interpret the two new features of pattern matching and Nint

Generally speaking, this keyword is not the most important, but the C ා team attaches great importance to pointer operation, which is a very positive signal.

2. Pattern matching improvements

Pattern matching is not a new feature. It has been improved in C ා 9 this time. Many friends may not be familiar with pattern matching. After all, it is a new play method of C ා 7, and almost every new version is tracking and improving. Let me popularize it first.

What problem does pattern matching solve

In the process of coding, you can’t miss itNested if / elseIn this case, sometimes the nesting even reaches 5 or 6 layers, especially affecting the readability of the code. I’ll give YY an example.

Nowadays, various places are issuing consumption coupons with different denominations. In order to realize the goal of thousands of people and thousands of faces, the issuing rules of consumption vouchers are as follows:

Gender Age region face value
male <20 Anhui 2000
male <40 Shanghai 4000
male surplus surplus 3000
female <20 Anhui 2500
female <60 Anhui 1500

If you use the traditional way, you must use all kinds of fancyif/elseTo implement, as follows:

static decimal GetTicketFee(string sex, int age, string area)
        {
            If (sex = = male)
            {
                If (age < 20 & area = = Anhui)
                {
                    return 2000;
                }
                else
                {
                    If (age < 40 & area = = Shanghai)
                    {
                        return 4000;
                    }
                    else
                    {
                        return 3000;
                    }
                }
            }
            else
            {
                If (age < 20 & area = = Anhui)
                {
                    return 2500;
                }
                If (age < 60 & area = = Anhui)
                {
                    return 1500;
                }
            }

            return 0;
        }

This kind of code readability is not generally bad, just like hadron said: look at all want to hit people… The problem is, is this code still saved??? Of course, it needs to be usedPattern matchingTo simplify, after all, it is for this problem. The modified code is as follows:

static decimal GetTicketFee_Pattern(string sex, int age, string area)
        {
            return (sex, age, area) switch
            {
                ("male", < 20, "Anhui") = > 2000,
                ("male", < 40, "Shanghai") = > 4000,
                (male)_ , ) => 3000,
                ("female", < 20, "Anhui") = > 2500,
                ("female", < 60, "Anhui") = > 1500,
                _ => 0
            };
        }

It’s amazing to see this kind of simplified codePattern matchingTo help you solve the scenario, next look at what the underlying IL code looks like.

C ා 9.0 is finally here. Let's take you to interpret the two new features of pattern matching and Nint

From the diagram, the decomposed code is worse than my handwriting, and I can’t make complaints about it.pattern matchingThere are all kinds of strange ways to play, which can absolutely make you jaw dropping. For more games, please refer to the official document: pattern matching

The most important thing about this feature is that you have to understand where its customer base is?

3: Summary

Generally speaking, these two features are more practical, especiallyPattern matchingResolve how much you have to write so bad code, hair care depends on it, quickly give it a favor!

Well, first of all, thank you for your reading. I hope this article will help you. Thank you.