What’s new in C# 9.0

csharp 9.0

Image source: Nikin

In my previous post, we learnt that Visual Studio Online is now renamed as Codespaces. You can check out the Codespaces article here. In this post we will see what’s new in C# 9.0 and what all features are going to be a part of it.

What’s new in C# 9.0

Around 20+ proposals are planned for C# 9, but it is unlikely that all of them will be implemented. Here we will discuss about the major features the Microsoft team is going to add to the next version of C#. This release is focused on support for immutable data shape representation.

Features

  • Object initializers with init-only properties
  • Create an immutable object using ‘data’ keyword – Records
  • Parameter null validation
  • Upper level statements
  • The “new” target-typed
  • With-expressions
  • Nominal records
  • Pattern matching

Object initializers with init-only properties

Object initializers are help us to create an object in a very flexible manner as shown

public class Vehicle
{
     public string Type { get; set; }
     public int NumberOfWheels { get; set; }
}
Above class can be created as
new Vehicle
{
    Type = "Two-wheeler",
    NumberOfWheels = 2
}

v.NumberOfWheels = 4; //Currently this post-initialization assignment works

 

But for above line to work, there is a limitation that the properties have to be mutable. Now in C# 9, there are init-only properties which fix this.There is an init accessor which can only be called during object initialization:

public class Vehicle
{
    public string Type { get; init; }
    public int NumberOfWheels { get; init; }
}

new Vehicle
{
    Type = "Two-wheeler",
    NumberOfWheels = 2
}

v.NumberOfWheels = 4; //Now since NumberOfWheels is an init property, this is not allowed and gives an error

With this init declaration, the code which initializes the properties is still valid, but any further assignments to the Type and NumberOfWheels properties gives an error since there are marked as init.

Create an immutable object using ‘data’ keyword – Records

In the above example we saw that we can mark individual properties as immutable using the init keyword. But what if you want to make the entire object to be immutable (unchanged) and behave more like a value. In this case, we can declare it as a record using the data keyword

public data class Vehicle
{
	public string Type { get; init; }
	public int NumberOfWheels {get; init; }
}

The data keyword on the Vehicle class declaration marks it as a record. By using the data keyword, we get several additional value-like behaviors on the object. In other words, records are to be seen more as data i.e. ‘values’ – data and less as objects. They are defined by their contents and not by their identity.

Parameter Null Validation

The exclamation operator i.e. ! can be place after any parameter list and the C# compiler instead will do a null checking code for that parameter. For example:

void MethodName(string lastname!) {
   //some code
}

The above code will be compiled into

void MethodName(string lastname!) {
if (lastname is null) {
    throw new ArgumentNullException(…);
}

Some rules for the above new operator

  • In a constructor, this validation will occur after the base class constructor fires.
  • In case of structs for e.g. where the parameter cannot be null, will result in a compile error.
  • Null validationisadded at the beginning of the method and it will validate in the same order as the parameters.
  • Null check on an out parameter witll throw a compiler error.
  • If a null validation is applied to an optional parameter with default value of null, it will show a compiler warning.
  • If you have marked a parameter as nullable explicitly for e.g (string? name!), it will show a compiler warning.

Upper-level statements

Currently, writing hello world program in C# for beginners can be confusing with all boilerplate code, but with C# 9.0, we can directly start writing statements like below

//Previous versions
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Foo Bar!");
    }
}

In C# 9.0, notice the upper-level statements are gone

using System;

Console.WriteLine("Foo Bar!");

In the above example, any codeis valid here but it will be allowed only in one code file since there can be only one main method.

The new Target-typed

Expression doesn’t need to say type it will come from context like below

//Previous versions
Person person = new Person("FirstName","LastName");

In C# 9.0, notice that we don’t specify ‘Person’ type again after new

Person person = new ("FirstName","LastName");

With-expressions

Normally, we create a new object of a particular type having some properties different than the earlier one. For e.g. take the Person object. If we want a new Person object with different last name, then we would have created a new Person object copying properties from existing object and only making the last name property different. Now C# 9.0 allows this using the with keyword expression. Note that it uses object initialize code to mark what will be different in the new object from the old object.

//Copy of person object with same properties except LastName
var new Person = person with { LastName = "Stark"}

Nominal Records

If you want data to be used for naming or labeling variables, then nominal data is useful. For e.g

data class Person {string FirstName, string LastName};    
var person = new person { Name = "Tony", LastName = "Stark"};    
var copyPerson = user with { Name = "Chris"};

Pattern matching

You can add patterns corresponding to relational operators. So you can now write the VehicleSpeed part of the above pattern as a nested switch expression. Note that > 5000 and < 3000 are relational patterns

VehicleSpeed s when s.Thresholdswitch
{
    > 100 => //some value,
    < 150 => //some value,
    _ => //some value,
},

Summary

In this post we learnt some of the new features in C # 9.0. Hope you liked this article. Please subscribe to my blog if you want new articles to appear right into your inbox. Till we meet on another post, stay safe and keep learning.

Hitesh Boricha

I have a little over a decade experience in the IT industry. Having worked in various roles in this industry, I am passionate about technology.

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.