When listening to a DotNetRocks episode I heard Mads Torgersen say that for C#9 immutability improvements are a large part of the new features. Today we take a look at two of those features “init” properties and “records”. Let’s get started.
Init Properties
When using object initializers a property must have both a get and a setter for this to work. This causes the objects to be mutable. For C# 9 a new feature has been introduced called ‘init’.
public class Book { private readonly string _title; private readonly string _author; public string Title { get => _title; init => _title; } public string Author { get => _author; init => _author; } }
This allows me to set the values of the object and access readonly properties, but you can only assign the values during object initialization. I can still use it like this:
var t = new Book { Title = "A great book",Author="Marco Sikkens"} //Works t.Title= "Another great book"; //doesnt work
Record Objects
The next feature that actually caused me to write this post is “Record” objects. Immutable objects are nice and useful when using threading but have one main disadvantage. You have to create a new instance when changing stuff. One way to solve this is using object builders like I’ve described here. However in C#9 a Record classes have been added.
public record Book { public string Title { get; init; } public string Author { get; init; } public string ISBN {get;init;} } public class Test { public void T() { var book = new Book { Title="Test", Author="Marco Sikkens", ISBN="123456789"}; var newBook = book with {Title = "Test 2"}; var newBook2 = book with {Title = "Test 2", Author="John Hancock"}; } }
This is actually quite nice and a improvement with the builder pattern. This way I don’t need that builder code which saves me a ton of time writing these.