Member-only story

C# Records vs Classes

William Rees
5 min readJan 29, 2024

--

With the release of C# 10 in November 2021 developers were introduced to a new concept called records, in this post I’ll outline some of the key differences between records and classes.

For this comparison I’ll only consider the default/common approach for creating class’ and records’, since a record is really just syntactic sugar on top of a class / struct the behavior is not isolated to records but by default they behave differently.

The record I’ll use for comparison is:

public record PointRecord(int X, int Y);

and the class is:

public class PointClass
{
public int X { get; set; }

public int Y { get; set; }
}

1. Mutability

Records are immutable because the properties are only settable when the record is created. A class can behave in a similar way if you use { get; init; } instead of { get; set; }

Records also support Nondestructive mutation which means that a record can be cloned and properties can be changed using the object initialize syntax for example

var point1 = new PointRecord(1, 2);
var point2 = point1 with { X = 2 };

this would be equivalent creating a new record with X = 2 and Y = 2as the value for Y is copied from point1.

--

--

William Rees
William Rees

Written by William Rees

Software engineer with 10+ years of experience. I primarily work on the Microsoft and .NET ecosystem and have extensive experience with Microsoft Azure

Responses (1)