© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2022
G. ByrneTarget C#https://doi.org/10.1007/978-1-4842-8619-7_26

26. C# 11

Gerard Byrne1  
(1)
Belfast, Ireland
 

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.

To amend the .csproj file for the specific project we are working on and allow us to use the preview features, the process is as follows:
  • In the Solution Explorer panel , double-click the project name.

  • Amend the XML to add <LangVersion>preview</LangVersion> to the code:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <LangVersion>preview</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

Raw String Literals

When we have looked at the use of strings particularly in Chapter 15 on string handling, we have seen different modifiers used with the strings. We used the verbatim , @, and the template literal, $, and we also read that we still need to escape things like double quotes. We will code an application to apply raw string materials.
  1. 1.

    Right-click the solution CoreCSharp.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose New Project.

     
  4. 4.

    Choose Console App from the listed templates that appear.

     
  5. 5.

    Click the Next button.

     
  6. 6.

    Name the project Chapter26 and leave it in the same location.

     
  7. 7.

    Click the Next button.

     
  8. 8.

    Choose the framework to be used, which in our projects will be .NET 6.0 or higher.

     
  9. 9.

    Click the Create button.

     
Now we should see the Chapter26 project within the solution called CoreCSharp .
  1. 10.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  2. 11.

    Click the Set as Startup Project option.

     
  3. 12.

    Right-click the Program.cs file in the Solution Explorer window.

     
  4. 13.

    Choose Rename.

     
  5. 14.

    Change the name to RawStringLiterals.cs.

     
  6. 15.

    Press the Enter key.

     
  7. 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.

Listing 26-1 shows an example of escaping, where we want to actually display a word or phrase with double quotes around it and we have to use “” at the start of the quoted word or phrase and at the end of the quoted word or phrase. We will add the Main() method , and inside it we will create a string literal that includes the double quotes “” at the start and end of a number of words. We will then write the string to the console.
  1. 17.

    Amend the code as shown in Listing 26-1.

     
namespace Chapter26
{
  internal class RawStringLiterals
  {
    static void Main(string[] args)
    {
      string rawStringLiterals =
        @"Kathleen Dollard Principal Program Manager, .NET
at Microsoft is quoted as saying about raw string literals
""If you work with strings literal that contain quotes or
embedded language strings like JSON, XML, HTML, SQL, Regex
and others, raw literal strings may be your favorite feature
of C# 11.""
and I think we may agree that this is a cool feature of C# 11.
https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/";
      Console.WriteLine(rawStringLiterals);
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-1

Escaped double quotes around a phrase using verbatim @

  1. 18.

    Click the File menu.

     
  2. 19.

    Choose Save All.

     
  3. 20.

    Click the Debug menu.

     
  4. 21.

    Choose Start Without Debugging.

     
Figure 26-1 shows the console window and we can see that the double quote escape sequence produces a single quote.

A series of text on the console window depicts double escape sequence open quotation mark close quotation mark produces a single quote.

Figure 26-1

Double quote escape sequence produces a single quote

  1. 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 .

We will now add a new raw string literal starting with three double quotes and ending with the same three double quotes and assign it to a new variable.
  1. 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.

     
and I think we may agree that this is a cool feature of C# 11.
https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/";
      Console.WriteLine(rawStringLiterals);
      Console.WriteLine($" *** C# 11 Raw String Literal ***");
      string rawStringLiterals11 = """
Kathleen Dollard Principal Program Manager, .NET at
Microsoft is quoted as saying about raw string literals
"If you work with strings literal that contain quotes or
embedded language strings like JSON, XML, HTML, SQL, Regex
and others, raw literal strings may be your favorite feature
of C# 11."
and I think we may agree that this is a cool feature of C# 11.
https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/"
""";
      Console.WriteLine(rawStringLiterals11);
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-2

New raw string literal starting and ending with three double quotes

  1. 24.

    Click the File menu.

     
  2. 25.

    Choose Save All.

     
  3. 26.

    Click the Debug menu.

     
  4. 27.

    Choose Start Without Debugging.

     
Figure 26-2 shows the console window and we can see that the double quotes have appeared around the words of the quote even though they were only single double quotes. The use of the new raw string literal starting with the three double quotes """ and ending with the same three double quote """ characters has worked as expected.

A series of bracketed texts on the console window depict raw string literal using double quotes.

Figure 26-2

Raw string literal using three double quotes """

  1. 28.

    Press the Enter key to close the console window.

     
We will now amend the raw string literal so that the last three double quote """ characters is indented. When a raw string literal is displayed, the position of the last three double quotes """ is crucial, since the first of the double quotes indicates the starting point for the text, the left margin if we wish to think of it like that. The text we have then gets displayed from this left position, and therefore none of the text can be positioned to the left of this position.
  1. 29.

    Amend the code as in Listing 26-3, to indent the end three double quotes by one space.

     
and I think we may agree that this is a cool feature of C# 11.
https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/";
      Console.WriteLine(rawStringLiterals);
      Console.WriteLine($" *** C# 11 Raw String Literal ***");
      string rawStringLiterals11 = """
Kathleen Dollard Principal Program Manager, .NET at
Microsoft is quoted as saying about raw string literals
“If you work with strings literal that contain quotes or
embedded language strings like JSON, XML, HTML, SQL, Regex
and others, raw literal strings may be your favorite feature
of C# 11."
And I think we may agree that this is a cool feature of C# 11.
https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/
 """;
      Console.WriteLine(rawStringLiterals11);
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-3

Text cannot be left of the first of the last three double quotes

  1. 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.

     

A series of text depicts an error message that informs about the spacing. The text reads, text is past the double quote.

Figure 26-3

Text is left of three double quotes """

  1. 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.

     
      Console.WriteLine($" *** C# 11 Raw String Literal ***");
      string rawStringLiterals11 = """
  Kathleen Dollard Principal Program Manager, .NET at
  Microsoft is quoted as saying about raw string literals
  "If you work with strings literal that contain quotes or
  embedded language strings like JSON, XML, HTML, SQL, Regex
  and others, raw literal strings may be your favorite feature
  of C# 11."
  and I think we may agree that this is a cool feature of C# 11.
  https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/
  """;
      Console.WriteLine(rawStringLiterals11);
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-4

Text must be one space past the last three double quotes

  1. 32.

    Click the File menu.

     
  2. 33.

    Choose Save All.

     
  3. 34.

    Click the Debug menu.

     
  4. 35.

    Choose Start Without Debugging.

     
Figure 26-4 shows the console window and we can see that the double quotes have marked the start of the text on the left-hand side and our text was positioned one space in from the double quotes.

A series of texts on the console window is positioned one space from the double quotes, which have marked the start of the texts on the left-hand side.

Figure 26-4

One space indented from """

  1. 36.

    Press the Enter key to close the console window.

     
We can see that raw string literals are a nice feature, but we can go further, because raw string literals can be interpolated by preceding them with a $.
  1. 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.

     
  and I think we may agree that this is a cool feature of C# 11.
  https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/
  """;
      Console.WriteLine(rawStringLiterals11);
      Console.WriteLine($" *** C# 11 Interpolated Raw String Literal ***");
      string companyName = "Microsoft";
      string languageName = "C# 11";
      int version = 11;
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-5

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.

Once we paste the text, we will replace the
  • 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}

This means we have used interpolation within the raw string literal.
  1. 38.

    Amend the code as in Listing 26-6.

     
      string companyName = "Microsoft";
      string languageName = "C# 11";
      int version = 11;
      string rawStringLiterals11V2 = $"""
  Kathleen Dollard Principal Program Manager, .NET at
  {companyName} is quoted as saying about raw string literals
  "If you work with strings literal that contain quotes or
  embedded language strings like JSON, XML, HTML, SQL, Regex
  and others, raw literal strings may be your favorite feature
  of {languageName}."
  and I think we may agree that this is a cool feature of C# {version}.
  https://devblogs.microsoft.com/dotnet/csharp-126-preview-updates/
  """;
      Console.WriteLine(rawStringLiterals11V2);
    } // End of Main() method
  } // End of class RawStringLiterals
} // End of namespace Chapter26
Listing 26-6

Interpolated raw string literal

  1. 39.

    Click the File menu.

     
  2. 40.

    Choose Save All.

     
  3. 41.

    Click the Debug menu.

     
  4. 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 {}.

C# 11 introduces a new feature to these string interpolations, where we can now span multiple lines. The text we have between the curly braces is parsed, and we can therefore include any legal C# code including new lines. In terms of producing readable code, this feature certainly helps.
  1. 1.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class

     
  4. 4.

    Change the name to NewLinesInterpolation.cs.

     
  5. 5.

    Click the Add button.

     
  6. 6.

    Amend the code to add a Main() method using the svm shortcut.

     
We will now create two string variables and then create an interpolated string, which uses these variables and which includes new lines in the formation of the interpolated string.
  1. 7.

    Amend the code as in Listing 26-7.

     
namespace Chapter26
{
  internal class NewLinesInterpolation
  {
    static void Main(string[] args)
    {
     string policyId = "AUT000001";
     string policyCoverage = "within the country of the policy.";
     string policyMessage = $"The policy {
        policyId
        } is limited to driving {
       policyCoverage
       }";
     Console.WriteLine(policyMessage);
    } // End of Main()
  } // End of NewLinesInterpolation class
} // End of Chapter26 namespace
Listing 26-7

New line in interpolated string

  1. 8.

    Click the File menu.

     
  2. 9.

    Choose Save All.

     
  3. 10.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  4. 11.

    Choose Properties.

     
  5. 12.

    Set the Startup object to be the NewLinesInterpolation.cs in the drop-down list.

     
  6. 13.

    Close the Properties window.

     
  7. 14.

    Click the Debug menu.

     
  8. 15.

    Choose Start Without Debugging.

     
Figure 26-5 shows the console window and we can see that the interpolated string has executed as expected.

A series of texts on the console window depicts execution of new lines in interpolated string.

Figure 26-5

New lines in interpolated string

  1. 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         ↑  ↑ ↑

We will now code an application where we will match the letters of a policy type against a series of patterns. We will iterate an array of policy types converting each policy type string to a character array and then pass the array to a method that will perform the matching. When a match is found, a string will be returned and is displayed to the console.
  1. 1.

    Right-click the Chapter26 project in the Solution Explorer window.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class ListPatterns.cs.

     
  5. 5.

    Double-click the ListPatterns.cs file to open it in the editor window.

     
  6. 6.

    Amend the code as in Listing 26-8, to create the Main() method.

     
namespace Chapter26
{
  internal class ListPatterns
  {
    static void Main(string[] args)
    {
    } // End of Main() method
  } // End of class ListPatterns
} // End of namespace Chapter26
Listing 26-8

Namespace with class and Main() method

  1. 7.

    Amend the code as in Listing 26-9, to create the array of policy types.

     
namespace Chapter26
{
  internal class ListPatterns
  {
    static void Main(string[] args)
    {
      // Declare and create an array of strings
      string[] policyType = { "CONDO", "LIFE", "AUTO", "RING", "ZUNKNOWNZ" };
    } // End of Main() method
  } // End of class ListPatterns
} // End of namespace Chapter26
Listing 26-9

Array of policy types added

Now we will iterate the array, and in each iteration we will take the array string item, convert it to a char array, and pass it to the method we will create next. We will then write the returned value to the console.
  1. 8.

    Amend the code as in Listing 26-10.

     
    static void Main(string[] args)
    {
      // Declare and create a array of strings
      string[] policyType = { "CONDO", "LIFE", "AUTO", "RING", "ZUNKNOWNZ" };
      /*
      Iterate the policyType array and convert the current
      item to a char array. Then pass the char array to the
      method which will check each letter against a pattern
      held in an array
      */
      foreach (string policy in policyType)
      {
        char[] charArr = policy.ToCharArray();
        Console.WriteLine(CheckPolicyType(charArr));
      } // End of foreach iteration
    } // End of Main() method
  } // End of class ListPatterns
} // End of namespace Chapter26
Listing 26-10

Iterate the array

Now we will create the method that accepts the char array, which holds the letters of the policy type. The method will use a switch construct to pattern match the list of characters, and when the appropriate pattern is found, the matching string is returned to the calling statement. In the pattern we will be using the slice pattern, which is two dots, .. and means zero or more characters. The pattern we will use to match our list is Z .. Z, which means starts with Z, then has zero or more characters, and then ends with the character Z. In the switch construct, we are also using a slice pattern in the default.
  1. 9.

    Amend the code as in Listing 26-11.

     
    } // End of Main() method
    /*
     Create a method that accepts a char array and then checks
     each letter of the char array against a pattern
     held in an array
     */
    public static string CheckPolicyType(char[] values)
    => values switch
    {
      ['A', 'U', 'T', 'O'] => $"Auto has a factor of 1",
      ['H', 'O', 'M', 'E'] => $"Home has a factor of 2",
      ['C', 'O', 'N', 'D', 'O'] => $"Condo has a factor of 3",
      ['B', 'O', 'A', 'T'] => $"Boat has a factor of 4",
      ['L', 'I', 'F', 'E'] => $"Life has a factor of 5",
      ['Z', .. ,'Z'] => $"Specialist policy has a factor of 5",
      [..] => $"Unknown policy type has a factor of 100"
    };
  } // End of class ListPatterns
} // End of namespace Chapter26
Listing 26-11

Method to match the list of policy type letters and return a string

  1. 10.

    Click the File menu.

     
  2. 11.

    Choose Save All.

     
  3. 12.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  4. 13.

    Choose Properties.

     
  5. 14.

    Set the Startup object to be the ListPatterns.cs in the drop-down list.

     
  6. 15.

    Close the Properties window.

     
  7. 16.

    Click the Debug menu.

     
  8. 17.

    Choose Start Without Debugging.

     
Figure 26-6 shows the console window and we can see that each of the policy type strings has been matched to one of the patterns.

A series of texts on the console window depicts list pattern Z, ellipsis, Z matching the policy Z UNKNOWN Z.

Figure 26-6

List pattern Z..Z matches the policy ZUNKNOWNZ

  1. 18.

    Press the Enter key to close the console window.

     
We will now add a new element, HARDWARE, to the array that does not fit the list pattern, and when we run the application, we will be given the “default” message.
  1. 19.

    Amend the code as in Listing 26-12, to add the additional element.

     
    static void Main(string[] args)
    {
      // Declare and create an array of strings
      string[] policyType = { "CONDO", "LIFE", "AUTO", "RING", "ZUNKNOWNZ", "HARDWARE" };
Listing 26-12

Add a new element to the array

  1. 20.

    Click the File menu.

     
  2. 21.

    Choose Save All.

     
  3. 22.

    Click the Debug menu.

     
  4. 23.

    Choose Start Without Debugging.

     
Figure 26-7 shows the console window and we can see that the HARDWARE policy type has been matched to the seventh pattern, [..].

A series of texts on the console window depicts the matching of hardware policy to the seventh pattern open bracket dot dot close bracket.

Figure 26-7

[..] has matched the policy type HARDWARE

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.

By using the discard pattern, in the last line of the CheckPolicyType() method , our code could be as Listing 26-13, and this would mean that every other pattern not found in the first six cases would fall under this “default” case.
  1. 24.

    Click the File menu.

     
  2. 25.

    Choose Save All.

     
  3. 26.

    Click the Debug menu.

     
  4. 27.

    Choose Start Without Debugging.

     
    public static string CheckPolicyType(char[] values)
    => values switch
    {
      ['A', 'U', 'T', 'O'] => $"Auto has a factor of 1",
      ['H', 'O', 'M', 'E'] => $"Home has a factor of 2",
      ['C', 'O', 'N', 'D', 'O'] => $"Condo has a factor of 3",
      ['B', 'O', 'A', 'T'] => $"Boat has a factor of 4",
      ['L', 'I', 'F', 'E'] => $"Life has a factor of 5",
      ['Z', .., 'Z'] => $"Specialist policy has a factor of 5",
      _ => $"Unknown policy type has a factor of 100"
    };
Listing 26-13

Using the discard, _, rather than the slice pattern [..]

Figure 26-8 shows the console window and we can see that the HARDWARE policy type has been matched to the discard pattern, _.

A series of texts on the console window depicts the matching of the hardware policy to the discard pattern, underscore.

Figure 26-8

Discard pattern _ has matched the policy type HARDWARE

Auto Default Struct

Prior to C# 11 all fields of a struct needed to be initialized in the constructor. We saw in Chapter 19 on structs an example of a Policy struct with four fields, and the constructor was used to initialize the field values. Listing 26-14 shows code that is similar to the Chapter 19 PolicyExample.cs class, but the initialization of the monthlyPremium field does not exist in the constructor . This causes a compile error in C# 10, as we will see when we code the example. We will code this example in the Chapter19 project.
  1. 1.

    Right-click the Chapter19 project, not the current Chapter26 project, in the Solution Explorer window.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class StructsExample.cs.

     
  5. 5.

    Double-click the StructsExample.cs file to open it in the editor window.

     
We will add the code to create a struct calling it Policy10, which has two fields and a constructor for the Policy10 struct where we do not initialize the field called monthlyPremium.
  1. 6.

    Amend the code as in Listing 26-14.

     
namespace Chapter19
{
    public struct Policy10
    {
      public int policy_number;
      public double monthlyPremium;
      public Policy10()
      {
        policy_number = 123456;
      } // End of user constructor
    }// End of Policy10 struct
  internal class StructsExample
  {
    static void Main(string[] args)
    {
      var myPolicy = new Policy10();
      Console.WriteLine(myPolicy.monthlyPremium);
    } // End of Main() method
  } // End of class StructsExample
} // End of namespace Chapter19
Listing 26-14

Policy10 struct where constructor does not initialize all fields

  1. 7.

    Hover over the Policy10 word in the constructor.

     
Figure 26-9 shows the pop-up window that will be displayed with an error message telling us that all fields must be assigned a value. In other words, the default value of the field is not activated. We might think annoying, but alas C# 11 can help us.

A pop-up window displays an error message that says all fields must be assigned a value before control is returned to the caller.

Figure 26-9

Struct field must be initialized

  1. 8.

    Add the code to initialize the monthlyPremium field as in Listing 26-15.

     
    public struct Policy10
    {
      public int policy_number;
      public double monthlyPremium;
      public Policy10()
      {
        policy_number = 123456;
        monthlyPremium = 99.00;
      } // End of user constructor
    }// End of Policy10 struct
Listing 26-15

Policy10 struct where constructor has initialized all fields

  1. 9.

    Click the File menu.

     
  2. 10.

    Choose Save All.

     
  3. 11.

    Right-click the Chapter19 project in the Solution Explorer panel.

     
  4. 12.

    Choose Set as Startup Project.

     
  5. 13.

    Right-click the Chapter19 project in the Solution Explorer panel.

     
  6. 14.

    Choose Properties.

     
  7. 15.

    Set the Startup object to be the StructsExample.cs in the drop-down list.

     
  8. 16.

    Close the Properties window.

     
  9. 17.

    Click the Debug menu.

     
  10. 18.

    Choose Start Without Debugging.

     
Figure 26-10 shows console output with the value from the one field we have chosen to display.

A console output that reads, monthly Premium field set when the constructor is called, hovers above a series of text.

Figure 26-10

The field value set by the constructor call

  1. 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.

We will now code this example in the Chapter26 project. The code will be the same as in Listing 26-14, with the initialization of the monthlyPremium field not being coded, and we will change the struct name to be Policy11 (C# 11).
  1. 20.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  2. 21.

    Choose Set as Startup Project.

     
  3. 22.

    Right-click the Chapter26 project in the Solution Explorer window.

     
  4. 23.

    Choose Add.

     
  5. 24.

    Choose Class.

     
  6. 25.

    Name the class StructsExample.cs.

     
  7. 26.

    Double-click the StructsExample.cs file to open it in the editor window.

     
  8. 27.

    Amend the code as in Listing 26-16.

     
namespace Chapter26
{
  public struct Policy11
  {
    public int policy_number;
    public double monthlyPremium;
    public Policy11()
    {
      policy_number = 123456;
    } // End of user constructor
  }// End of Policy11 struct
  internal class StructsExample
  {
    static void Main(string[] args)
    {
      var myPolicy = new Policy11();
      Console.WriteLine(myPolicy.monthlyPremium);
    } // End of Main() method
  } // End of class StructsExample
} // End of namespace Chapter26
Listing 26-16

Policy11 struct where constructor has not initialized all fields

  1. 28.

    Click the File menu.

     
  2. 29.

    Choose Save All.

     
  3. 30.

    Right-click the Chapter26 project in the Solution Explorer panel.

     
  4. 31.

    Choose Properties.

     
  5. 32.

    Set the Startup object to be the StructsExample.cs in the drop-down list.

     
  6. 33.

    Close the Properties window.

     
  7. 34.

    Click the Debug menu.

     
  8. 35.

    Choose Start Without Debugging.

     
Figure 26-11 shows console output with the default value from the one field we have chosen to display. This example clearly shows that the new auto default struct does indeed use the default value of a struct field if it is not initialized within the constructor.

A console output that reads, monthly Premium field value set when the constructor is called and is assigned the default type value, hovers on top of a series of text.

Figure 26-11

The field default value is used in C# 11.

  1. 36.

    Press the Enter key to close the console window.

     

Warning Wave 7

The Microsoft site https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/warning-waves tells us the following:

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.

So, if we opt in, we will see errors in our code that we may not have seen prior to opting in. C# 11 introduces a new warning wave that can produce a warning when a type is declared with all lowercase letters. According to the Microsoft documentation, any new keywords in C# will all be lowercase ASCII characters . This means that when we create our own types, for example, a class or struct, we need to be cognizant that our name may conflict with a keyword, if we use all lowercase. We can avoid this situation by
  • 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:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
                   <LangVersion>preview</LangVersion>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
                 <TreatWarningsAsErrors>true</TreatWarningsAsErrors>
    <StartupObject>Chapter26.StructsExample</StartupObject>
  </PropertyGroup>
</Project>
  1. 1.

    Right-click the Chapter26 project in the Solution Explorer window.

     
  2. 2.

    Choose Add.

     
  3. 3.

    Choose Class.

     
  4. 4.

    Name the class warningwave.cs yes, small letters.

     
  5. 5.

    Double-click the warningwave.cs file to open it in the editor window.

     
  6. 6.

    Make sure the code looks like that shown in Listing 26-17, with the class name being small letters.

     
namespace Chapter26
{
  internal class warningwave
  {
  } // End of class warningwave
} // End of namespace Chapter26
Listing 26-17

Namespace with class

  1. 7.

    Hover over the word warningwave, the class name/

     
Figure 26-12 shows the pop-up window that will be displayed with a warning message.

A pop-up window displays a text that reads, ellipsis indicating a warning under the class name as it is all lower- above the class name starting with a lowercase letter.

Figure 26-12

Wave warning for class name with lowercase starting letter

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 ?.

An illustration of a small circle surrounded by circles of increasing size depicts that the target has been reached.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.240.230