Member-only story
C# Records vs Classes
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 = 2
as the value for Y
is copied from point1.