Take you to the C#7 feature code example

Source: Internet
Author: User
Tags bitmask case statement
take you to the C#7 feature code example:

Tuple value types

. NET provides a tuple (tuple) type, but there are a variety of problems when used specifically in C #. Because a tuple type is a reference type, in some code that is fairly sensitive to performance, you are likely to avoid the overhead of GC by using it. At the same time, the tuple type is immutable, although it makes cross-thread sharing more secure, but it also means that each time a change is made, a new object must be assigned.

To address this problem, C # 7 will provide a tuple of value types. This is a mutable type, which is more efficient for code that takes performance into consideration. At the same time, as a value type, it produces a copy each time it is allocated, so there is little risk of multithreading problems.

You can create a tuple from the following syntax:

var result = (5, 20);

You can also choose to name the values in the tuple, which is not required, but makes the code more readable.

var result = (Count:5, sum:20);

You might think, "great features, but I can write them myself." But the next feature is the highlight.

Multiple return values

In a Class C-style language, it is always a hassle to return two values in a function. You can only choose to encapsulate the result in a structure, or use an output parameter. Like many functional programming languages, C # chooses the first way to provide you with this feature:

(int, int) Tally (ienumerable<int> list)

As you can see, there's a basic problem with using a generic tuple here: We won't know what each field does. Therefore, C # chooses to name the result by a compiler gimmick:

(int Count, int Sum) Tally (ienumerable<int> list)

We need to emphasize here that C # does not generate a new anonymous type, and you still get a tuple, but the compiler will assume that its properties are count and sum, not Item1 and Item2. Therefore, the following lines of code are all equivalent:

var result = Tally (list); Console.WriteLine (Result. ITEM1); Console.WriteLine (Result. Count);

Please note that we do not yet have a multi-assignment syntax, and if this syntax is eventually implemented, then it might be used like this:

(count, sum) = Tally (list);

In addition to providing simple functional functions, the usefulness of multiple return values is also reflected in the writing of asynchronous code, because out parameters are not allowed in the async function.

Pattern matching: Improved switch syntax block

VB and functional programmers complain most about C # that the switch statements in C # are very limited in functionality. VB developers want to be able to match the range, while the developers accustomed to F # or Haskell want to be able to use exploded pattern matching. C # intends to provide both of these features.

When you make pattern matching for a type, you can create a variable to hold the result of the transformation. For example, when you use a switch statement with a System.Object, you can write the following code:

case int x:

If the object is a numeric type, the variable x is assigned a value. Otherwise, the program will check the next Case statement block in order from top to bottom. If you want to make a more specific match, you can also use range checking:

case int x when x > 0:case int y:

In this example, if the object is a positive integer, the x code block is executed. If the object is a 0 or a negative integer, and the y code block is executed.

If you need to check for null values, you can only use the following syntax:

Case NULL;

Pattern matching: Decomposition

So far, we've just shown some incremental improvements to the features that are already in VB, and the real power of pattern matching is decomposition, which can take an object completely apart and consider the following syntax:

If (person is Professor {Subject are var s, FirstName is "Scott"})

This code accomplishes two things:

    1. It creates a local variable s and assigns it to ((professor) person). Subject.

    2. It performs an equality check ((professor) person). FirstName = = "Scott".

If you overwrite it with C # 6 code, this is the case:

var temp = person as professor;if (temp! = null && temp. FirstName = = "Scott") {    var s = temp. Subject

In the final release, we expect to see both of these improvements to the switch statement block at the same time.

Reference returns

Reference passing for big data structures is much faster than value passing, because the latter requires a copy of the entire structure. Similarly, returning a reference to a large data structure can increase speed.

In a language like C, a reference to a struct can be returned by a pointer. This approach poses a common problem where the memory pointed to by the pointer may have been recycled for some reason.

C # avoids this problem by using a reference, which is itself a pointer to a rule attached. The most important rule is that you cannot return a reference to a local variable. If you try to do this, the stack information referenced by the variable becomes inaccessible when the function returns.

In Microsoft's presentation code, the reference it returns points to a structure in an array. Since it is essentially a pointer to an element in the array, it can then be modified to the group itself. For example:

var x = ref Firstelement (myArray) x = 5; Myarray[0] now equals 5

The use case for this syntax is highly performance-sensitive code, which is not required in most applications.

Binary literals (binary literals)

This release also introduces a small feature, binary literals. This syntax is just a simple prefix, for example 5 can be expressed as "0b0101". The primary use case for this feature is to set up flag-based enumerations and to create bitmask (bitmask) for interoperability with C-style languages.

Local functions

A local function refers to a function defined in another function. At first glance, the local function appears to be just a slightly better syntax than an anonymous function. But it actually has several advantages:

    • First, you do not need to assign it a delegate to save the function. This not only reduces the memory pressure, but also allows the compiler to inline the function.

    • Second, when you create a closure, you do not need to assign an object to it, because it can directly access local variables. This can also improve performance because it also reduces the pressure on the GC.

By the second rule, you will not be able to create a delegate that points to a local function. This is an advantage for the organization of code because you do not need to create a separate function and pass the state of an existing function as an explicit parameter.

Improvements to some classes

The last feature demonstrated is a new way to work with partial classes. In the past, the application of some classes was based on the concept of code generation first. The generated code will contain a series of methods that developers can choose to implement to adjust the behavior of the class.

With the new "replace" syntax, developers have a new option to write the code in the most straightforward way, and then introduce the code generator and rewrite the methods. Here's a simple example of how the developer will write the code:

public string FirstName {get; set;}

Simple and clear, but completely incompatible with the way XAML-style apps are written. Therefore, the code generator generates the following code:

private string m_firstname;static readonly PropertyChangedEventArgs S_firstname_eventargs =new PropertyChangedEventArgs ("FirstName") Replace public string FirstName {    get {        return m_firstname;    }    set {        if (M_firstname = = value)            return;    M_firstname = value;    PropertyChanged?. Invoke (this, m_firstname_eventarg);}

With the "Replace" keyword, the generated code will replace the handwritten code directly, adding the missing features. In this example, we can even handle some of the troublesome parts that developers often overlook, such as caching EventArgs objects.

Although this official example is used only for property change notifications, this technique can be used in a variety of "aspect-oriented programming (AOP)" scenarios, such as injecting logging, security checks, parameter validation, and other cumbersome boilerplate code in code.

If the reader wants to actually understand these features, you can watch the video "The Future of C #" in Channel 9.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.