.NET Core 3.x and .NET Standard 2.1 support C# 8.0 syntax, introduce many functional features, and add new feature syntax: Readonly members, default interface methods, pattern matching enhancements, attribute patterns, Tuple patterns, position patterns, switch expressions, using declarations, static local functions, asynchronous flows, indexes and ranges, null merge assignments, etc. This article will explain the new knowledge points of C# 8.0.
Index and scope
The following .NET types support both indexes and ranges: Array, String, Span, and ReadOnlySpan. List supports indexes, but not ranges
Example 1: The birthday of the person who obtained the ID number
Example 2: Get the contents of the last bit of the string
Example 3: Remove the last bit
switch
expression
Attribute mode
Tuple pattern
Location mode
Some types include a Deconstruct method that deconstructs its properties into discrete variables. If you have access to the Deconstruct method, you can use Position Patterns to check the properties of an object and use those properties for patterns. Consider the following Point class that contains a Deconstruct method for creating discrete variables for X and Y:
Also, consider the following enumeration of the various positions that represent the quadrant:
The following method uses the position pattern to extract the values of x and y. It then uses the when clause to determine the quadrant for that point:
Null merge assignments
Constructor expressions
using statement
The using declaration is a variable declaration preceded by the using keyword. It instructs the compiler to declare variables to be handled at the end of the closed scope. For example, the code for writing a text file is as follows:
In the previous example, the file is processed when the right parentheses of the method are reached. This is the end of the range of the declared file. The preceding code is equivalent to the following code using the classic using statement:
In the previous example, the file is processed when the right parentheses associated with the using statement are reached. In both cases, the compiler will generate a call to Dispose(). If the expression in the using statement is not available, the compiler will generate an error.
Resources
The hyperlink login is visible.
The hyperlink login is visible. |