C# 9 came out over a couple of years ago and only recently did I have a look into what actually changed. A bit late, but it’s always better to be late than never. The first thing that I got really excited about with c# 9 is the addition of the with expression. This seems to follow some javascript syntax that allows one object’s values to be copied very easily, and change a few properties if desired.

With syntax

Consider a Car class:

public class Car { 
    public string Make {get; set;}
    public string Model {get;set;}
}

With the with expression, we can then create a Car and create another car with the exact same properties, with the exception of one or more different values.

// Create the car
Car premiumMazda = new Car() { Make = "CX5", Model = "Premium" };

// If we want to create a new Car object that has the same properties as `premiumMazda`, we can do the following
Car standardMazda = premiumMazda with { Model = "Standard" };

This feels so clean to me as there have been times in the past where I want an object with the same values as another object, except for maybe one or two properties. Previuosly, I would have to use something like Automapper to make it easy to create a new object with the same property values. Now, it comes straight out of the box as a language feature, which is amazing!

I think I came across this sort of expression first in Javascript. It was pretty easy for an object’s values to be copied across to another object using the Object.assign() method. Now it’s in C#!! Brilliant!

Record types

Another feature that Microsoft added to C#9 is a record data type. We can create immutable data object with the record type. I don’t really use immutable data types in my current workplace and I’m not sure when I would do that for now.

public record Planet(string Name, int NumberOfMoons);

static void Main() { 
    var planet = new Planet("Earth", 1);
    Console.WriteLine(planet); 
    // Will output: Planet {Name = "Earth", NumberOfMoons = 1}
}

That being said, I think the ToString() method being able to output the properties values is pretty cool. This can be quite useful when logging as I wouldn’t need to convert models into JSON and instead just use the ToString() method of the record.

References

Microsoft Documentation Object assign