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

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

This is the part 3 of the series in which I shall take up the following changes to the C# language:

  • Extended property patterns
  • Improvements on lambda expressions
  • Allow const interpolated strings
  • Record types can seal ToString()
  • Improved definite assignment
  • Caller argument expression attribute
  • Assignment and declaration in same deconstruction

YouTube Version:

You can see it as a YouTube video here

Extended property patterns

Pattern matching was introduced in C# 7.0, and has been improved in every major language version since then. C# 10 is no exception, and makes it possible to use more concise property patterns. For instance, before C# 10, if you wanted to check nested properties in a pattern, you had to write something like this:

if (employee is { FirstName: { Length: > 20} })
    Console.WriteLine("It is a long name!");

This was a little more verbose than we’d like. With extended property patterns, you can now write it like this:

if (employee is { FirstName.Length: > 20} })
    Console.WriteLine("It is a long name!");

Let’s see this in action with our Visual Studio 2022 project that we have created for this series of posts. I have loaded the project WhatsNewInCSharp that we have built in part 1 and part 2

I now create an Employee class in a new Employee.cs file with the code as follows:

internal class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

The employee class is a simple class with just two properties. We shall now demonstrate the extended property pattern by editing the Program class to look as below:

using WhatsNewInCSharp;
Employee employee = new Employee();
Console.WriteLine("Enter the employee first name:");

if (!String.IsNullOrEmpty(employee.FirstName = Console.ReadLine()))
{
    
    if (employee is { FirstName.Length: > 10 }) // C#10 extended property pattern
        //if (employee is { FirstName: { Length: > 10 } }) //this is still valid in C#10
        Console.WriteLine("It is a longgg name!");
    else
    {
        Console.WriteLine("The name is not that long");
    }
    
}

On running the app, we get the following screenshot (Fig 1)

Fig 1

This proves our statement on extended property. Bear in mind that due to the backward compatibility feature of the language, the earlier syntax (till C# 9) will still work.

Lambda improvements

C# 10 includes many improvements to how lambda expressions are handled:

  • Lambda expressions may have a natural type, where the compiler can infer a delegate type from the lambda expression or method group.
  • Lambda expressions may declare a return type when the compiler can’t infer it.
  • Attributes can be applied to lambda expressions.

These features make lambda expressions more similar to methods and local functions. They make it easier to use lambda expressions without declaring a variable of a delegate type, and they work more seamlessly with the new ASP.NET Core Minimal APIs.

Automatically infer a “natural” type for a lambda

Historically, C# lambda expressions didn’t have an intrinsic type. The expression (int n) => n % 2 == 1 didn’t have a type on its own; the type was determined based on what it was assigned to, e.g.:

Func<int, bool> isOdd = (int n) => n % 2 == 1;

Now, the compiler will try to automatically infer a “natural” delegate type for a lambda, making it possible to use var to make the code more concise and readable:

// isOdd is implicitly of type Func<int, bool>
var isOdd = (int n) => n % 2 == 1;

The inferred type will always be a variant of the System.Func<...> or System.Action<...> delegate types, depending on the parameters and return type. Note that the compiler will only be able to infer a type if it has all the information it needs, especially the parameter types; it can’t infer a type for n => n % 2 == 1, since it doesn’t know the type of n.

Another example of the inferred type (C# 10) is below

var parse = (string s) => int.Parse(s);

The compiler can infer parse to be a Func<string, int>. The compiler chooses an available Func or Action delegate, if a suitable one exists.  When a lambda expression has a natural type, it can be assigned to a less explicit type, such as System.Object or System.Delegate:

object parse = (string s) => int.Parse(s);   // Func<string, int>
Delegate parse = (string s) => int.Parse(s); // Func<string, int>

Method groups (that is, method names without parameter lists) with exactly one overload have a natural type:

var read = Console.Read; // Just one overload; Func<int> inferred
var write = Console.Write; // ERROR: Multiple overloads, can't choose

Explicitly specify the return type for a lambda

C# 10 makes it possible to specify a return type for a lambda. This wasn’t necessary before, since a lambda had to be assigned to a specific delegate type anyway, but with natural delegate type inference, there might be cases where you want the return type to be different from what is automatically inferred. For instance

var oneTwoThreeArray = () => new[]{1, 2, 3}; // inferred type is Func<int[]>
var oneTwoThreeList = IList<int> () => new[]{1, 2, 3}; // same body, but inferred type is now Func<IList<int>>

Apply attributes to lambda expression

Currently, only named methods (including local functions) can have attributes; in C# 10, lambda expression can have them as well:

Func<int, bool> isEven = [Pure] n => n % 2 == 0;

Constant interpolated strings

Before C# 10 it was possible to concatenate strings, the string interpolation functionality existed but did not allow to have interpolated string constants. this is now possible with C# 10 for readability reasons. Let’s look at an example below before C# 10 when constants were concatenated as below.

using System;

namespace DemoCsharp
{
    public class Demo
    {
        private const string scheme = "https";
        private const string LoginUri = "login";
        private const string HomeUri = "home";

        private const string dev = scheme + "://localhost:5001";

        private const string LoginUriDev = dev + "/" + LoginUri;
        private const string HomeUriDev = dev + "/" + "myaccount" + "/" + HomeUri;

    }
}

With C# 10 it is now possible to use interpolated string constants and rewrite the above code as below:

using System;

namespace DemoCsharp10
{
    public class Demo
    {
        private const string scheme = "https";
        private const string LoginUri = "login";
        private const string HomeUri = "home";

        private const string dev = $"{scheme}://localhost:5001";

        private const string LoginUriDev = $"{dev}/{LoginUri}";
        private const string HomeUriDev = $"{dev}/myaccount/{HomeUri}";
    }
}

Record types can seal ToString

In C# 10, you can add the sealed modifier to the ToString() method in the base class which when you attempt to override in a derived record type, ends up in a compile error. Sealing the ToString method prevents the compiler from synthesizing a ToString method for any derived record types. A sealed ToString ensures all derived record types use the ToString method defined in a common base record type.

using System;

namespace DemoCsharp10Console
{
    public record Person
    {
        public string FirstName {  get; init; }

        public string LastName { get; init; }

        public sealed override string ToString()
        {
            return $"My name is {FirstName} {LastName}";
        }
    }
    
    public record Student : Person
    {
        public override string ToString() // Error CS0239 'Student.ToString()': cannot override inherited member 'Person.ToString()' because it is sealed
        {
            return $"My name is {FirstName} {LastName}";
        }
    }
}

Improved definite assignment

C# produces errors if you use a value that has not been definitely assigned. C# 10 understands your code better and produces less spurious errors. These same improvements also mean you’ll see less spurious errors and warnings for null references.

Prior to C# 10, there were many scenarios where definite assignment and null-state analysis produced warnings that were false positives. These generally involved comparisons to boolean constants, accessing a variable only in the true or false statements in an if statement, and null coalescing expressions.

Caller argument expression attribute

The new [CallerArgumentExpression] attribute lets you capture the expression passed to a method as a string.

I will now switch over to Visual studio 2022 and start working with our Program class in the WhatsNewInCSharp project and add the following code at the bottom

//checking CallerArgumentExpression attribute
static void LogExpression<T>(T value, [CallerArgumentExpression("value")] string expression = null)
{
    Console.WriteLine($"{expression}: {value}");
}


var person = new Employee("Thomas", "Levesque");
LogExpression(person.FirstName); //

On running the application I get the following console output:

Fig. 2

The expression parameter is optional, and if it isn’t specified, the compiler will automatically pass the expression used as the value parameter, as a string. In other words, the call to LogExpression in the code above is equivalent to doing this:

LogExpression(person.FirstName, "person.FirstName");

A common use case is a method that checks that an argument isn’t null:

So we paste the following code below the last line of code above

static void EnsureArgumentIsNotNull<T>(T value, [CallerArgumentExpression("value")] string expression = null)
{
    if (value is null)
        throw new ArgumentNullException(expression);
}

 static void Foo(string name)
{
    EnsureArgumentIsNotNull(name); // if name is null, throws ArgumentNullException: "Value cannot be null. (Parameter 'name')"
  
}
Foo(null);

On running the application we get the error message:

Fig 3

Assignment and declaration in same deconstruction

What is deconstruction of a tuple?

C# features built-in support for deconstructing tuples, which lets you unpackage all the items in a tuple in a single operation. Let’s now see what is a tuple ? A tuple provides a lightweight way to retrieve multiple values from a method call. But once you retrieve the tuple, you have to handle its individual elements.

Beginning in C# 10, you can mix variable declaration and assignment in a deconstruction.

Let’s again switch back to Visual Studio 2022 project and add the following at the end in the Program class:

public class Example
{
    public static void GetTuples()
    {
        string city = "Raleigh";
        int population = 458880;

        (city, population, double area) = QueryCityData("New York City");

        Console.WriteLine(city);
        Console.WriteLine(population);
        Console.WriteLine(area);
    }

    private static (string, int, double) QueryCityData(string name)
    {
        if (name == "New York City")
            return (name, 8175133, 468.48);

        return ("", 0, 0);
    }
   
    
}

Then call the GetTuples() method like such from outside the Example class (say below the call to Foo() method :

Example.GetTuples();

If you run the application now, you’ll get the following screenshot (Fig. 4):

Fig. 4

Which is the data returned from the tuples by the GetTuples() method.

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.