Said's Blog

C# - Records

September 04, 20224 min read
image

C# 9 introduces a new keyword - record. It's a reference type, but with value-based comparison. It makes an object immutable and behave like a value type. The whole object can be immutable if the init keyword is set on each property, if you are using an implicit parameterless constructor.

Record keyword

Record keyword

With expression

With expression

Value base comparison

Value base comparison

Positional records

Positional records

Records and inheritance

Records and inheritance

Value based comparison and inheritance

Value based comparison and inheritance

FAQ about Records

  1. Are records a value type ?
  2. 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.

  3. Can a Record have a Struct and classical object as properties ?
  4. Yes it’s definitely possible.

  5. Are with expressions available for Structs and classes ?
  6. No. It gives a compilation error.

  7. Are Records immutable by default ?
  8. No. They are only acting as value type by default, you have to set all properties with init keyword.