SHARE:

Introducing C# 9: Questions & answers about Records

Introduction

You have been many to ask me questions about the records in C# 9 I described in my latest article: https://anthonygiretti.com/2020/06/17/introducing-c-9-records/. In this article I will answer them for my greatest pleasure as well as yours 🙂

How can I test C# 9 preview features, especially Records ?

Records are not available on VS 2019 16.7 preview 2 with .NET 5 SDK preview installed, but improved pattern matching is.
So if you want to test Records, and the rest, you have for now to download Linqpad6 beta here: https://www.linqpad.net/linqpad6.aspx#beta

To enable C# 9, go to Edit > Preferences > Query and tick the Use Roslyn Daily checkbox:

Are records a value type ?

No! Records are reference type, they behave like value type (like Structs) for comparison. Like Structs they override Equals virtual method to have “value-based equality”, comparing each field of the struct by calling Equals on them recursively. – https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/#value-based-equality – Microsoft

It means ReferenceEquals (and ==) are comparing Records object reference, unlike Struct which will always return false. Examples:

Can a class have a Record as property ?

Yes it’s definitely legal:

Can a Record have a Struct and classical object as properties ?

Yes it’s definitely legal:

Are with expressions available for Structs and classes ?

No. And you will a compilation error:

Are Records immutable by default ?

No. They are only acting as value type by default, you have to set all properties with init keyword.

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: