C# New Features
With the latest C# release, C# 11, expected in November 2022, we will be treated to some new features to help us develop code.
We can use the features of C# 11 in their current form, prior to official release , by amending the project file, .csproj, to inform it that we wish to use the preview feature of the language. The .csproj file defines the project content, platform requirements, and, importantly for us, the language versioning information. It may also contain information about servers such as a database or web server.
In the Solution Explorer panel , double-click the project name.
Amend the XML to add <LangVersion>preview</LangVersion> to the code:
Raw String Literals
- 1.
Right-click the solution CoreCSharp.
- 2.
Choose Add.
- 3.
Choose New Project.
- 4.
Choose Console App from the listed templates that appear.
- 5.
Click the Next button.
- 6.
Name the project Chapter26 and leave it in the same location.
- 7.
Click the Next button.
- 8.
Choose the framework to be used, which in our projects will be .NET 6.0 or higher.
- 9.
Click the Create button.
- 10.
Right-click the Chapter26 project in the Solution Explorer panel.
- 11.
Click the Set as Startup Project option.
- 12.
Right-click the Program.cs file in the Solution Explorer window.
- 13.
Choose Rename.
- 14.
Change the name to RawStringLiterals.cs.
- 15.
Press the Enter key.
- 16.
Double-click the RawStringLiterals.cs file to open it in the editor window.
We will start by creating a string that uses the verbatim identifier, the @ special character. When we use the @, the string literal will be interpreted verbatim , precisely as it appears. Any escape sequences such as the backslash will be interpreted literally. On the other hand, the double quote escape sequence, “”, is not interpreted literally and it will produce one double quotation mark.
- 17.
Amend the code as shown in Listing 26-1.
Escaped double quotes around a phrase using verbatim @
- 18.
Click the File menu.
- 19.
Choose Save All.
- 20.
Click the Debug menu.
- 21.
Choose Start Without Debugging.
- 22.
Press the Enter key to close the console window.
C# 11 introduces us to raw string literals as a new format for string literals. This new feature means string literals can now contain arbitrary text, which means we can now include embedded quotes or new lines or whitespace and other special characters , all without having to use escape sequences. The new raw string literal is depicted by starting with at least three double quote """ characters, and it must end with the same number of double quote characters .
- 23.
Amend the code as in Listing 26-2, to use the new raw string literal, starting with three double quotes and ending with the same three double quotes.
New raw string literal starting and ending with three double quotes
- 24.
Click the File menu.
- 25.
Choose Save All.
- 26.
Click the Debug menu.
- 27.
Choose Start Without Debugging.
- 28.
Press the Enter key to close the console window.
- 29.
Amend the code as in Listing 26-3, to indent the end three double quotes by one space.
Text cannot be left of the first of the last three double quotes
- 30.
Hovering over the red underline in the spaces before the word Kathleen will display an error message that informs us about spacing, as shown in Figure 26-3.
- 31.
Amend the code as in Listing 26-4, to move all the text so that it is one space past the end three double quotes and ensure that the red underline disappears.
Text must be one space past the last three double quotes
- 32.
Click the File menu.
- 33.
Choose Save All.
- 34.
Click the Debug menu.
- 35.
Choose Start Without Debugging.
- 36.
Press the Enter key to close the console window.
- 37.
Amend the code as in Listing 26-5, to declare and initialize three variables, two of data type string and the other of data type int.
New WriteLine() statement and three variables declared
We will now add a new interpolated raw string literal, which means we use the dollar sign, $, before the three double quotes. This new string will be called rawStringLiterals11V2 . The text that we assign to it will be the same text as we have in the string variable rawStringLiterals11.
Word Microsoft with the variable companyName enclosed in open and close curly braces, that is, {companyName}
First C #11 phrase with the variable languageName enclosed in open and close curly braces, that is, {languageName}
11 in the second C #11 phrase with the variable version enclosed in open and close curly braces, that is, {version}
- 38.
Amend the code as in Listing 26-6.
Interpolated raw string literal
- 39.
Click the File menu.
- 40.
Choose Save All.
- 41.
Click the Debug menu.
- 42.
Choose Start Without Debugging.
The console window will show the final display of text, which is identical to the text shown in Figure 26-4, but this code has used interpolated values .
Nice feature. Thank you, C# 11.
New Lines in String Interpolations
Interpolation can be defined as the insertion of something of a different nature into something else. When we have looked at the use of strings, we have seen how to use string interpolation with the special character, $, which identifies the string literal as an interpolated string. An interpolated string is a string literal that might contain interpolation expressions. Essentially, it is a fancy word for joining our strings with other non-string variables or values, and to build a string interpolation, we will make use of the curly braces {}.
- 1.
Right-click the Chapter26 project in the Solution Explorer panel.
- 2.
Choose Add.
- 3.
Choose Class
- 4.
Change the name to NewLinesInterpolation.cs.
- 5.
Click the Add button.
- 6.
Amend the code to add a Main() method using the svm shortcut.
- 7.
Amend the code as in Listing 26-7.
New line in interpolated string
- 8.
Click the File menu.
- 9.
Choose Save All.
- 10.
Right-click the Chapter26 project in the Solution Explorer panel.
- 11.
Choose Properties.
- 12.
Set the Startup object to be the NewLinesInterpolation.cs in the drop-down list.
- 13.
Close the Properties window.
- 14.
Click the Debug menu.
- 15.
Choose Start Without Debugging.
- 16.
Press the Enter key to close the console window.
List Patterns
C# 11 introduces a new feature called the list pattern , which allows for matching against lists and arrays. When we use the list pattern, we can use the slice pattern, .., allowing us to match zero or more elements. The syntax used in a list pattern is values surrounded by square brackets.
When we slice an array, we are getting a range of elements from within the array. If we had an array with the elements 1,2,3,4,5,6 and we were to slice the array from index 2 to index 5 using the command slice(2,5), we would get the values 3,4,5. The command slice(2,5) means start at index 2 and stop at index 5, which is exclusive, and therefore the element at 5 is not included.
Index 0 1 2 3 4 5 6
Array 1 2 3 4 5 6
Sliced elements ↑ ↑ ↑
- 1.
Right-click the Chapter26 project in the Solution Explorer window.
- 2.
Choose Add.
- 3.
Choose Class.
- 4.
Name the class ListPatterns.cs.
- 5.
Double-click the ListPatterns.cs file to open it in the editor window.
- 6.
Amend the code as in Listing 26-8, to create the Main() method.
Namespace with class and Main() method
- 7.
Amend the code as in Listing 26-9, to create the array of policy types.
Array of policy types added
- 8.
Amend the code as in Listing 26-10.
Iterate the array
- 9.
Amend the code as in Listing 26-11.
Method to match the list of policy type letters and return a string
- 10.
Click the File menu.
- 11.
Choose Save All.
- 12.
Right-click the Chapter26 project in the Solution Explorer panel.
- 13.
Choose Properties.
- 14.
Set the Startup object to be the ListPatterns.cs in the drop-down list.
- 15.
Close the Properties window.
- 16.
Click the Debug menu.
- 17.
Choose Start Without Debugging.
- 18.
Press the Enter key to close the console window.
- 19.
Amend the code as in Listing 26-12, to add the additional element.
Add a new element to the array
- 20.
Click the File menu.
- 21.
Choose Save All.
- 22.
Click the Debug menu.
- 23.
Choose Start Without Debugging.
We could also have used a discard instead of the slice pattern in the switch construct. Discards, _, can be used where any value is accepted at that position. The discard pattern can be used in pattern matching with the switch expression, and every expression, including null, always matches the discard pattern.
- 24.
Click the File menu.
- 25.
Choose Save All.
- 26.
Click the Debug menu.
- 27.
Choose Start Without Debugging.
Using the discard, _, rather than the slice pattern [..]
Auto Default Struct
- 1.
Right-click the Chapter19 project, not the current Chapter26 project, in the Solution Explorer window.
- 2.
Choose Add.
- 3.
Choose Class.
- 4.
Name the class StructsExample.cs.
- 5.
Double-click the StructsExample.cs file to open it in the editor window.
- 6.
Amend the code as in Listing 26-14.
Policy10 struct where constructor does not initialize all fields
- 7.
Hover over the Policy10 word in the constructor.
- 8.
Add the code to initialize the monthlyPremium field as in Listing 26-15.
Policy10 struct where constructor has initialized all fields
- 9.
Click the File menu.
- 10.
Choose Save All.
- 11.
Right-click the Chapter19 project in the Solution Explorer panel.
- 12.
Choose Set as Startup Project.
- 13.
Right-click the Chapter19 project in the Solution Explorer panel.
- 14.
Choose Properties.
- 15.
Set the Startup object to be the StructsExample.cs in the drop-down list.
- 16.
Close the Properties window.
- 17.
Click the Debug menu.
- 18.
Choose Start Without Debugging.
- 19.
Press the Enter key to close the console window.
Now in C# 11, this annoying feature of initialization has been changed, and the compiler ensures that all fields of a struct type are initialized to their default value as part of executing a constructor . This can be a great feature for us because any field not initialized by a constructor will automatically be initialized by the compiler. Even with the uninitialized fields, the application code will compile since those fields not explicitly initialized will be allocated the default value their type.
- 20.
Right-click the Chapter26 project in the Solution Explorer panel.
- 21.
Choose Set as Startup Project.
- 22.
Right-click the Chapter26 project in the Solution Explorer window.
- 23.
Choose Add.
- 24.
Choose Class.
- 25.
Name the class StructsExample.cs.
- 26.
Double-click the StructsExample.cs file to open it in the editor window.
- 27.
Amend the code as in Listing 26-16.
Policy11 struct where constructor has not initialized all fields
- 28.
Click the File menu.
- 29.
Choose Save All.
- 30.
Right-click the Chapter26 project in the Solution Explorer panel.
- 31.
Choose Properties.
- 32.
Set the Startup object to be the StructsExample.cs in the drop-down list.
- 33.
Close the Properties window.
- 34.
Click the Debug menu.
- 35.
Choose Start Without Debugging.
- 36.
Press the Enter key to close the console window.
Warning Wave 7
New warnings and errors may be introduced in each release of the C# compiler. When new warnings could be reported on existing code, those warnings are introduced under an opt-in system referred to as a warning wave. The opt-in system means that you shouldn't see new warnings on existing code without taking action to enable them. Warning waves are enabled using the AnalysisLevel element in your project file.
When <TreatWarningsAsErrors>true</TreatWarningsAsErrors> is specified, enabled warning wave warnings generate errors. Warning wave 5 diagnostics were added in C# 9. Warning wave 6 diagnostics were added in C# 10. Warning wave 7 diagnostics were added in C# 11.
Using at least one uppercase character or an underscore or even a digit.
Enabling the warning waves for the project. This is an opt-in and can be enabled by double-clicking the project name and adding one line of code to the XML properties as shown:
- 1.
Right-click the Chapter26 project in the Solution Explorer window.
- 2.
Choose Add.
- 3.
Choose Class.
- 4.
Name the class warningwave.cs – yes, small letters.
- 5.
Double-click the warningwave.cs file to open it in the editor window.
- 6.
Make sure the code looks like that shown in Listing 26-17, with the class name being small letters.
Namespace with class
- 7.
Hover over the word warningwave, the class name/
Chapter Summary
This chapter has shown us that .NET and C# are continually evolving, and as developers we need to be aware of new features, so we can make informed choices when we code our application. Not every new version will offer us features that we will want to apply in our code, but learning is a lifelong process and we need to keep track of language changes.
Having completed our final chapter, we know that we have achieved so much and have reached the target we set ourselves from the outset. We should be immensely proud of what we have achieved. We are now in a great position to look back at the applications we coded and think to ourselves, Maybe I could have coded the examples in a different way, in a better way. Yes, the examples in the book have helped us Target C# and learn the language, but we must use our knowledge to program our applications the way we feel comfortable, but within the confines of existing coding standards.
We have made the journey to Target C#. We should celebrate and then think about our next target, Target ?.