Learn all new features in C# 10 (Part 1)

Learn all new features in C# 10 (Part 1)

This is a series of blog posts intended to list and discuss all the new features of the programming language C# whose latest version C# 10 was released recently with Visual Studio 2022 in the .Net Conference 2021.

This is the part 1 of the series in which I shall be discussing the

  • Record Structs and
  • Improvement of struct types

YouTube version:

https://youtu.be/-lnwe0Ubkcg

All the new features

In a nutshell, the following are all the features, that are incorporated in this latest avatar of the C# language:

  • Record Structs
  • Improvement of struct types
  • String Handlers Interpolation
  • Global Using Directives
  • File-scoped namespace declaration
  • Extended property patterns
  • Lambda extension improvements
  • Const interpolated strings allowed
  • Record types can seal ToString()
  • Improved definite assignment
  • Allow both declaration and assignment in the same deconstruction
  • Allow AsyncMethodBuilder attribute on methods
  • CallerArgumentExpression attribute
  • Enhanced #line pragma

Understanding Records

In order to understand “Record Structs”, we shall have to know about “What a record is ?”. Now beginning with C# 9, the record keyword is used to define a reference type that provides built-in capability of encapsulating data. Records have a value based equality even for reference types, e.g. class.
Record types with immutable properties can be created by using positional parameters or standard property syntax

 public record Person(string FirstName, string LastName); // immutable properties with positional params
        public record Person1 // immutable properties with standard property syntax
        {
            public string FirstName { get; init; } = default!;
            public string LastName { get; init; } = default!;
        };

Record types with mutable properties and fields can also be created:

public record Person
{
    public string FirstName { get; set; } = default!;
    public string LastName { get; set; } = default!;
};

Enough of theory and let’s get our hands dirty!! So let’s see the above code snippet in action in Visual Studio 2022 in a console project. Open Visual Studio 2022

Fig. 1

Click Create a new project in the above Fig. 1 In the Create a new project dialog (Fig. 2)

Fig. 2

Highlight Console App and Click Next. On Configure your new project dialog (Fig. 3), give it any suitable name (I chose WhatsNewInCSharp), pick up a suitable location on your machine and click Next

Fig. 3

On the Additional information dialog (Fig. 4), select .NET 6.0 (LTS) out of the available options and Create

Fig. 4

Now add a class file to the project called RecordDemo.cs and paste the code below within the internal class RecordDemo which was auto-generated when the file was added.

public record Person(string FirstName, string LastName); // immutable properties with positional params
        public record Person1 // immutable properties with standard property syntax
        {
            public string FirstName { get; init; } = default!;
            public string LastName { get; init; } = default!;
        };
        public record Person2 // Mutable properties 
        {
            public string FirstName { get; set; } = default!;
            public string LastName { get; set; } = default!;
        };
        public  static void Main()
        {
            var p = new Person("Kaushik", "Roy");
           // p.FirstName = "Tim";
            var p1 = new Person1 { FirstName = "John", LastName = "William" };
           // p1.FirstName = "Henry";
            var p2 = new Person2 { FirstName = "Robbie", LastName = "William" };
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
            p2.FirstName = "John"; p2.LastName = "George";
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
        }

Click Ctrl + F5 to run without debugging and you get the following out put on Command window (Fig. 5)

Fig. 5

This output is as expected as we are setting the values of mutable properties through code which we can reassign with different values for and it would still work as below:

 public  static void Main()
        {
            var p = new Person("Kaushik", "Roy");
           // p.FirstName = "Tim";
            var p1 = new Person1 { FirstName = "John", LastName = "William" };
           // p1.FirstName = "Henry";
            var p2 = new Person2 { FirstName = "Robbie", LastName = "William" };
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
            p2.FirstName = "John"; p2.LastName = "George";
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
            p2.FirstName = "Mack"; p2.LastName = "Brown";
            Console.WriteLine(p2.FirstName + " "+ p2.LastName);
        }
Fig 6.

That was the easier part of mutable properties that were assigned after declaration and could later be changed any number of times. Now let’s see what happens when we uncomment the following code in the snippet below

 public  static void Main()
        {
            var p = new Person("Kaushik", "Roy");
            p.FirstName = "Tim"; //Uncommented Code
            var p1 = new Person1 { FirstName = "John", LastName = "William" };
            p1.FirstName = "Henry";//Uncommented Code 
            var p2 = new Person2 { FirstName = "Robbie", LastName = "William" };
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
            p2.FirstName = "John"; p2.LastName = "George";
            Console.WriteLine(p2.FirstName + " " + p2.LastName);
            p2.FirstName = "Mack"; p2.LastName = "Brown";
            Console.WriteLine(p2.FirstName + " "+ p2.LastName);
        }

If we inspect the code in Visual Studio (Fig. 7)

Fig. 7

It shows a red squiggly line at two places as in Fig. 7. On mouseover, it shows a compile error as seen in the Fig 8 which essentially means that we can’t reassign an immutable record which was declared either as positional parameter or standard property syntax and already assigned previously. (Note then both “p” and “p1” are immutable instances of an immutable Person record

Records are distinct from classes in that record types use value-based equality. Two variables of a record type are equal if the record type definitions are identical, and if for every field, the values in both records are equal. In contrast, Two variables of a class type are equal if the objects referred to are the same class type and the variables refer to the same object.

Record structs

C# 10 adds record structs so that you can define records as value types. Record struct types are value types, like other struct types. They implicitly inherit from the class System.ValueType. The modifiers and members of a record struct are subject to the same restrictions as those of structs

Improvements of Structure Types

C# 10 introduces the following improvements related to structure types:

  • You can declare an instance parameterless constructor in a structure type and initialize an instance field or property at its declaration.
  • A left-hand operand of the with expression  can be of any structure type or an anonymous (reference) type.

Now let’s discuss these two points in more detail through our Visual Studio project. We now add a class to our WhatsNewInCSharp project naming it StructureImprovements as below:

Fig. 8

Now paste the following code within the internal class StructureImprovements which was auto generated on adding the class file.

public readonly struct Measurement
{
    public Measurement()
    {
        Value = double.NaN;
        Description = "Undefined";
    }

    public Measurement(double value, string description)
    {
        Value = value;
        Description = description;
    }

    public double Value { get; init; }
    public string Description { get; init; }

    public override string ToString() => $"{Value} ({Description})";
}

public static void Main()
{
    var m1 = new Measurement();
    Console.WriteLine(m1);  // output: NaN (Undefined)

    var m2 = default(Measurement);
    Console.WriteLine(m2);  // output: 0 ()

    var ms = new Measurement[2];
    Console.WriteLine(string.Join(", ", ms));  // output: 0 (), 0 ()
}

After changing the startup object in the project property window (or .csproj file), run the application by pressing Start Without Debugging icon (or Ctrl + F5) and you’ll get the outputs as in the commented lines above:

Fig. 9

As the preceding example shows, the default value expression ignores a parameterless constructor and produces the default value of a structure type, which is the value produced by setting all value-type fields to their default values (the 0-bit pattern) and all reference-type fields to null. Structure-type array instantiation also ignores a parameterless constructor and produces an array populated with the default values of a structure type.

Left Hand Operator of With Expression

Now, let’s discuss the other improvement : A left-hand operand of the with expression  can be of any structure type or an anonymous (reference) type.

To show this, let’s dive straight into our Visual Studio project and create a new class file named WithExpressionEx.cs and paste the following code within the default internal class “WithExpressionEx” created from the template

public struct NamedPoint
            {
                public NamedPoint()
                {
                  Name = string.Empty;
                    ValueX = 0;
                    ValueY = 0;
                }

                public NamedPoint(string name, int x, int y)
                { 
                    Name = name;
                    ValueX = x;
                    ValueY = y;
                }
                public string Name { get; init; }
                public int ValueX { get; init; }
                 public int ValueY { get; init; }
        }

        

        public static void Main()
        {
            var p1 = new NamedPoint("A", 0, 0);
            Console.WriteLine($"{nameof(p1)}: {p1.Name},{p1.ValueX},{p1.ValueY}");  // output: p1: NamedPoint { Name = A, X = 0, Y = 0 }

            var p2 = p1 with { Name = "B", ValueX = 5 };
            Console.WriteLine($"{nameof(p2)}: {p2.Name},{p2.ValueX},{p2.ValueY}");  // output: p2: NamedPoint { Name = B, X = 5, Y = 0 }

            var p3 = p1 with
            {
                Name = "C",
                ValueY = 4
            };
            Console.WriteLine($"{nameof(p3)}: {p3.Name},{p3.ValueX},{p3.ValueY}");  // output: p3: NamedPoint { Name = C, X = 0, Y = 4 }

            var NamedPoint1 = new
            {
                Name = "Rory",
                X = 100,
                Y = 200
            };
            var NamedPoint2 = NamedPoint1 with { Name = "Johnny", X = 300 };
            Console.WriteLine(NamedPoint1);
            Console.WriteLine(NamedPoint2);


        }

If we now run the above code with Ctrl + F5, we get the output as below

Fig. 10

The output in Fig. 10 demonstrates that the variables p2 and p3 which are the left operands of the with expressions are struct types (as they are extending p1, a struct instance of the struct NamedPoint) . Also NamedPoint1 is an anonymous type which is changed with NamedPoint2 as anonymous type, which is the left hand operands of the with expression as below

var NamedPoint2 = NamedPoint1 with { Name = "Johnny", X = 300 };

Proving the new features of C# 10

At this juncture, you may well say “How will you prove that C# 10 has these features added to it that were non-existent in the previous versions?” Well… well… well… the answer lies in the question itself!! So simply test these code snippets in C# 9.0 by adding the <LangVersion>9.0</LangVersion> node within the PropertyGroup of the project file (.csproj), so the edited project file looks like :

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

After changing to C# 9, there are squiggly lines showing compile error (Fig. 11) in RecordDemo.cs file, which as seen on mouseover is self-explanatory

Fig. 11

Similarly, the StructureImprovement class shows the following compile error (Fig. 12):

Fig. 12

Lastly, if we change the LangVersion to 10.0 (or remove the node alltogether), it will again build without error

Follow Me Here

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.